简体   繁体   English

承诺解决命令并等待

[英]promise resolution order and await

I've got this piece of code: 我有这段代码:

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

In Google Chrome Version 61.0.3163.91 (Official Build) (64-bit) when I run it from a <script> , I got the following results: <script>运行Google Chrome 61.0.3163.91(正式版本)(64位)时,得到以下结果:

first then 
after await
second then

but when I copy/paste the code into the console and run it, I've got: 但是,当我将代码复制/粘贴到控制台中并运行它时,我得到了:

first then
second then
after await

node.js 8.5.0 behaves similarly. node.js 8.5.0的行为类似。

What is the proper order and why there's a difference? 正确的顺序是什么,为什么会有区别?

// edit //编辑

another interesting thing is that firefox 55.0.2 (64-bit) for this code: 另一个有趣的事情是此代码的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() 

logs: 日志:

first then
second then
third then
after await
forth then

The proper way of doing this is adding a await before the Promise.resolve() that does the "first then" and "second then" console logs. 正确的方法是在Promise.resolve()之前添加一个await ,该await将执行“第一个然后是”和“第二个然后是”控制台日志。 That way it'll wait for that promise to be done before it moves on to the console log for "after wait" 这样,它将等待承诺完成,然后再进入控制台日志进行“等待后”

This is how you're meant to do it. 这就是您要做的方式。

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM