javascript - 为什么我们需要返回一个 promise 解析?

标签 javascript node.js asynchronous async-await

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 关键字,上述代码将无法按预期工作。我不明白为什么我们需要写一个返回? Promise 的 resolve 方法本质上不就是返回一个值吗?

最佳答案

I do not understand why do we need to write a return?

因为如果您不这样做,履行回调的返回值将是未定义,就像任何其他函数一样,这意味着由该then创建的promise的履行值code> 调用将是未定义,而不是结果

这个履行处理程序根本没有任何理由,它没有做任何有用的事情,它只是在 promise 履行中引入了一个额外的异步“tick”。只需删除它即可:

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

您在评论中说过:

I understand that the part was not needed at all to be added. but I added it to understand Promises and in principle it should work, in my opinion.

这是因为我在上面第一段中提到的原因:否则,该函数将返回 undefined (隐式)。下面是ab之间的区别。您可能会想到简洁箭头语法,其中函数体只是一个表达式,返回是隐式的,如下面的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 。没有理由创建另一个 promise ;履行处理程序的返回值将用于解析返回的 promise then。不需要额外的。

关于javascript - 为什么我们需要返回一个 promise 解析?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67861395/

相关文章:

javascript - 有没有办法从 dojo 的 NumberSpinner 中删除逗号?

javascript - 许多 jquery ui 对话框

node.js - NodeJS Express session 在页面刷新后过期

node.js - 如何通过 node.js mongodb 驱动程序将验证器添加到现有集合?

c# - 析构函数中的异步操作

java - GWT 使用异步回调进行同步/阻塞调用

javascript - 是否可以将多个异步社交按钮加载器合并为一个?

javascript - 如何使用 CSS 或 JS 创建像 Jamendo 的页脚一样的页脚?

javascript - REACT- DOM 突变警告含义

node.js - 后端和前端在不同端口上运行,CORS 错误