我有这段代码:
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/