The execution sequence when returning a Promise object in promise then mehod

Viewed 121

The code is:

Promise.resolve().then(() => {
    console.log(0);
    return Promise.resolve(4);
}).then((res) => {
    console.log(res)
})

Promise.resolve().then(() => {
    console.log(1);
}).then(() => {
    console.log(2);
}).then(() => {
    console.log(3);
}).then(() => {
    console.log(5);
}).then(() =>{
    console.log(6);
})

And the result is: 0 1 2 3 4 5 6.

Why log 4 is after log 3? What is the special thing happened when returning a promise object in .then method?

1 Answers

Javascript runs an event loop.

Here is my guess.

Promise.resolve() creates a promise which will be resolved in the next iteration. And every then block will be execute in the next iteration after the previous block finish. So here is the execution order:

Iteration 1: Created 2 promises (name them A and B) which will be resolved in Iteration 2

Iteration 2: Promise A resolves. Promise B resolves

Iteration 3: then block of Promise A executes, which prints 0 and creates a new promise (name it C) which will be resolved in Iteration 4. First then block of the Promise B executes, which prints 1.

Iteration 4: Second then block of Promise B executes, which prints 2. Promise C resolves. (Since Promise C is added to the event loop later than Promise B, Promise B resolves before Promise C)

Iteration 5: Third then block of Promise B executes, which prints 3. then block of Promise C executes, which prints 4.

Iteration 6: Forth then block of Promise B executes, which prints 5.

Iteration 7: Fifth then block of Promise B executes, which prints 6.

Related