在下面的代码中,return
不返回等待的值。我怎样才能使诺言在返回之前得到解决。因此,我想result
成为SUCCESS
一个承诺。
const foo = async()=>{
try{
let a = await new Promise((resolve)=>{
resolve('SUCCESS')
})
console.log("this is inside the try block");
return a
}catch{
console.log('error')
}
}
let result = foo();
console.log(result);
foo
是一个异步函数,它将返回一个promise。为了获得承诺的结果,您需要将一个then
方法链接到它:
const foo = async()=>{
try{
let a = await new Promise((resolve)=>{
resolve('SUCCESS')
})
console.log("this is inside the try block");
return a
}catch{
console.log('error')
}
}
foo().then(result => console.log(result));
更新:
要使用返回的值,可以在then
方法内部使用它,也可以使用结果调用另一个函数。
foo().then(result => {
console.log(result);
//do what you want with the result here
});
要么:
foo().then(result => {
someFunction(result);
});
function someFunction(result) {
console.log(result);
//you can also do what you want here
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句