繁体   English   中英

返回不等待异步函数

[英]return does not await async function

在下面的代码中, return不返回等待的值。 我能做什么,以便在返回之前解决承诺。 因此,我希望resultSUCCESS而不是承诺。

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM