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
(隐式)。下面是a
和b
之间的区别。您可能会想到简洁箭头语法,其中函数体只是一个表达式,返回
是隐式的,如下面的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/