return 不等待异步函数

return does not await async function

在下面的代码中,return 不是 return 等待的值。我能做什么,所以承诺将在 returning 之前解决。因此我希望 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 是一个异步函数,它将 return 一个承诺。要获得承诺的结果,您需要将一个 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));

更新:

要使用 returned 值,您可以在 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
}