简体   繁体   中英

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:

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.

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:

 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. 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() 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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