javascript - return 不等待异步函数

标签 javascript async-await es6-promise

在下面的代码中,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/

相关文章:

javascript - Webpack 中多个入口点的通用样板

javascript - 在 JavaScript 中检查整数或 float 的最简洁方法是什么?

c# - 如何使用 await 简单安全地调用可为空的委托(delegate)

c# - HttpClient GetStringAsync - 它永远不会回来

node.js - mocha/chai 和 ES6 Promise 的奇怪断言失败

javascript - JQuery 循环重复结果

javascript - Sublime Text 3 PHP 语法不高亮显示

c# - 单元测试和多个异步任务

javascript - Bluebird 用于并行独立任务

javascript - 如何使用js Promise消除厄运金字塔