Search code examples
javascriptes6-promise

How is this Promise working in javascript


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

Promise
.resolve()
.then(() => console.log(4))
.then(() => console.log(5))
.then(() => console.log(6));

Answer: 1 4 2 5 3 6

May someone explain me how is it working?

Why it doesnt execute 1,2,3,4,5,6 ?


Solution

  • A .then callback runs in a microtask, which only run once currently running synchronous code is complete. Here, the synchronous code initializes two Promises which resolve immediately, with Promise.resolve.

    Microtasks resolve in order, so at the end of the script, there are two microtasks in the queue: the first one which was put onto the queue was () => console.log(1), so that gets logged first. At this point, 1's Promise resolved, so the next .then (2) was put onto the microtask queue. The second one which was put onto the queue was () => console.log(4), so that gets logged second, and 5 gets put onto the microtask queue. Then 2 runs and pushes its next .then onto the queue (3), then 4 runs and pushes its next .then (6) onto the queue. Etc.

    // queue:
    [1, 4]
    // 1 gets logged
    // 2 gets pushed
    [4, 2]
    // 4 gets logged
    // 5 gets pushed
    [2, 5]
    // 2 gets logged
    // 3 gets pushed
    [5, 3]
    ...
    

    If you had waited for the first Promise's whole Promise chain to fully resolve before continuing onto the second Promise.resolve, they'd all run in order, as you're expecting:

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

    The above occurs because the Promise constructed by the .resolve().then( ...) Promise chain will only resolve once the final Promise in the chain resolves - that is, after 3 gets logged.