简体   繁体   中英

Order of execution for Promises

I am reading this documentation about Promises and I don't understand something.

const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

wait().then(() => console.log(4));
Promise.resolve().then(() => console.log(2)).then(() => console.log(3));
console.log(1);

There is this example which outputs 1 2 3 4 .

So, it is normal that 1 is printed first, but why is 2 3 next and not 4 ? They are both inside a then() , 4 is inside a setTimeout but it has no milliseconds passed as parameter.

The setTimeout is the entire reason. Try this in contrast:

const wait2 = ms => new Promise(resolve => resolve());

wait2().then(() => console.log(4));
Promise.resolve().then(() => console.log(2)).then(() => console.log(3));
console.log(1);

Where the wait function resolves with no timeout. This does what you expect, 1423

Even if you don't pass a number to setTimeout , the javascript interpreter will wait until the processing queue is cleared before before running the contents of a setTimeout

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