返回不等待异步功能

幻影

在下面的代码中,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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章