在下面的代码中,return
不返回等待的值。我能做什么,以便在返回之前解决 promise 。因此,我希望结果
是SUCCESS
而不是 promise 。
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 。要获得 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
}
关于javascript - return 不等待异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60357157/