首页 > 解决方案 > 为什么我们需要返回一个 promise resolve?

问题描述

async function f() {

  let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("done!"), 1000)
  });

  let result = await promise; // wait until the promise resolves (*)

  return result; // "done!"
}
f().then(result => {
  return Promise.resolve(result);
}).then(r => console.log(r))

如果我从倒数第二行中删除return关键字,则上述代码无法按预期工作。我不明白为什么我们需要写return?难道promise的resolve方法本质上不就是返回一个值吗?

标签: javascriptnode.jsasynchronousasync-await

解决方案


不明白为什么要写return?

因为如果你不这样做,履行回调的返回值将是undefined,与任何其他函数一样,这意味着由该then调用创建的承诺的履行值将是undefined而不是result

完全没有理由使用该履行处理程序,它没有做任何有用的事情,它只是在承诺履行中引入了一个额外的异步“滴答”。只需将其删除:

f().then(result => console.log(result))

在评论中你说:

我知道根本不需要添加该部分。但我添加它是为了理解 Promises,在我看来,原则上它应该可以工作。

这是因为我在上面第一段中提到的原因:否则,函数返回undefined(隐式)。a这就是下面和下面的区别b。您可能正在考虑简洁的箭头语法,其中函数的主体只是一个表达式并且return是隐式的,如下c所示:

const a = () => {
    42;
};
const b = () => {
    return 42;
};
const c = () => 42; // No `{` just after the `=>`

console.log(a()); // undefined
console.log(b()); // 42
console.log(c()); // 42

在这种情况下,您将使用:

f().then(result => result) // If you want that there to understand it better
.then(result => console.log(result))

注意那里没有Promise.resolve。没有理由创造另一个承诺;履行处理程序的返回值将用于解析then返回的承诺。不需要额外的。


推荐阅读