Leo Messi
Leo Messi

Reputation: 6206

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.

Upvotes: 0

Views: 40

Answers (1)

TKoL
TKoL

Reputation: 13932

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

Upvotes: 2

Related Questions