javascript - 为什么 async await 函数返回一个值,而 promise 函数返回一个未定义的值?

标签 javascript promise async-await

我正在尝试使用 async-await 和 promise 来理解以下 2 个示例函数。

我希望这两个函数都返回“输出”,但使用 promise 的函数返回一个未定义的。

为什么会这样?我已经在 promise.resolve().then() 中返回了值,但毕竟没有返回任何值。

我在处理我的项目时遇到了这个问题。我正在使用 promise 方法返回一个值,但没有返回任何值。然后我使用 async-await 解决了它,但我不明白为什么?

async function asyncFunction(input) {
  try {
    let output = await Promise.resolve("output");
    return output;
  } catch (err) {
    console.log(err);
  }
}

function promiseFunction(input) {

    Promise.resolve().then(function() {
      return "output";
    }).catch(function(err){
      console.log(err);
    })
}

async function run() {
  let a = await asyncFunction();
  let b = await promiseFunction(); 

  console.log("async function output: " + a); //async function output: output
  console.log("promise function output: " + b); //promise function output: undefined
}

run();


我希望 asyncFunction() 和 promiseFunction() 都返回值“output”,但 promiseFunction 返回的是 undefined。

最佳答案

async 函数总是返回 promise 。如果您在普通函数中省略 return 语句,例如:

function doSomething(x) {
  x.y = 2;
}

然后返回undefined。

doSomething({}) === undefined // true

如果在 async 函数中省略 return 语句

async function doSomething(x) {
  x.y = 2;
}

它返回一个未定义的 promise

doSomething({}).then(result => result === undefined); // resolves to be true

在您的非 async 函数中,您不会返回任何内容。您需要返回 Promise.resolve().then(...) 行。这是使用 async/await 语法的好处之一。无需担心正确链接您的 promise 和返回。只做你的工作,在需要的地方等待,然后返回值。

关于javascript - 为什么 async await 函数返回一个值,而 promise 函数返回一个未定义的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58158075/

相关文章:

javascript - 为什么这个异步生成器会导致 JavaScript 运行时挂起?

javascript - 无法从异步 Promise 执行器函数中抛出错误

javascript - 如何导出由 async/await 方法返回的对象

c# - 等待后 HttpContext.Current 为空(仅在单元测试中)

javascript - 谷歌建议结果空数据参数

javascript - 使用 $httpBackend 模拟 $http 调用更改预期的 url Angular

javascript - Angular.forEach 循环无法正常工作

clojure - 当 Clojure promise 实现或失败时,如何听取它?

javascript - 将 promise 的包装快速路由返回到 app.use()

javascript - 无法通过 sequelize.authenticate() 方法使用异步等待