javascript - promise 解决顺序并等待

标签 javascript node.js google-chrome promise async-await

我有这段代码:

af = async () => {
    Promise.resolve()
    .then(x => console.log("first then"))
    .then(x => console.log("second then"))
    await Promise.resolve()
    console.log("after await")
}

af()

Google Chrome 版本 61.0.3163.91(正式版)(64 位) 当我从 <script> 运行它时,我得到了以下结果:

first then 
after await
second then

但是当我将代码复制/粘贴到控制台并运行它时,我得到了:

first then
second then
after await

node.js 8.5.0 的行为类似。

什么是正确的顺序,为什么会有差异?

//编辑

另一个有趣的是 firefox 55.0.2(64 位) 对于这段代码:

af = async () => {
    Promise.resolve()
    .then(x => console.log("first then"))
    .then(x => console.log("second then"))
    .then(x => console.log("third then"))
    .then(x => console.log("forth then"))
    await Promise.resolve()
    console.log("after await")
}

af()

日志:

first then
second then
third then
after await
forth then

最佳答案

正确的做法是在 Promise.resolve() 之前添加一个 await 来执行“first then”和“second then”控制台日志。这样它将等待完成该 promise ,然后再转到控制台日志以进行“等待后”

这就是您的本意。

af = async () => {
    await Promise.resolve() // NOTE: I added a "await" before the Promise.resolve()
    .then(x => console.log("first then"))
    .then(x => console.log("second then"))
    await Promise.resolve()
    console.log("after await")
}

af()

关于javascript - promise 解决顺序并等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46254408/

相关文章:

javascript - 如何使用普通 JavaScript 代码重新启动或终止 Google Chrome?

javascript - Chrome扩展消息传递: verify the sender

javascript - 在 Phaser 3 中设置快照的位置

javascript - Javascript JQuery 中的 CSS - 多重转换

javascript - 显示解析时间的计时器 c#

node.js - 蒙戈数据库。限制子文档仅具有 `projection`给定字段的方法(即过滤器)?

node.js - 使用 MongoDB 聚合时 - 如何过滤掉没有聚合子项的结果?

javascript - 在 https 上运行安全 Web 套接字需要什么?

node.js - 构建具有不同数量参数的 HTTP 请求?

javascript - 如何从扩展程序获取 Chrome DevTools 源编辑器中的光标位置?