![](/img/trans.png)
[英]Clarification on order of Promise resolution using Async/Await
[英]promise resolution order and 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()
从<script>
运行Google Chrome 61.0.3163.91(正式版本)(64位)时,得到以下结果:
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
,该await
将执行“第一个然后是”和“第二个然后是”控制台日志。 这样,它将等待承诺完成,然后再进入控制台日志进行“等待后”
这就是您要做的方式。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.