javascript - 为什么我们需要返回一个 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方法本质上不就是返回一个值吗?
解决方案
不明白为什么要写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
返回的承诺。不需要额外的。
推荐阅读
- python - 如何在张量流的神经网络中应用权重约束?
- c++ - 在 Windows 资源管理器中打开公共文档文件夹
- python - 熊猫 - 将日期增加 1
- c# - 使用 AutoMapper + 依赖注入进行映射时访问目标属性(非类型)
- javascript - 如何在反应中使用 howler.js?
- scheduling - 使用间隔进行调度时如何在 CP 中获取当前时间
- reactjs - React Native - Tipsi-stripe 错误 - '无法读取未定义的属性'init''
- c++ - 变量只能全局“声明”,不能修改/(单独初始化)
- c# - 使用带有 x509 证书的 IIS 托管 WCF 服务进行身份验证
- python - 如何在 Python 中为 Google Analytics Reporting API(REST 方法)获取 oauth2-token