[英]return does not await async function
在下面的代码中, 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
是一个异步函数,它将返回一个承诺。 要获得承诺的结果,您需要将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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.