DEV Community

Yo
Yo

Posted on

Titbits: Promises

// Example 1:

const p = Promise.resolve('A');

p.then(function (val) {
  console.log(val);
  p.then(function () {
    console.log('D');
  });
  console.log('B');
});

p.then(function () {
  console.log('C');
});
Enter fullscreen mode Exit fullscreen mode

// Example 2:

const p = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('A');
  }, 100);
});

p.then(function (val) {
  console.log(val);
  p.then(function () {
    console.log('D');
  });
  console.log('B');
});

p.then(function () {
  console.log('C');
});
Enter fullscreen mode Exit fullscreen mode

What is the output of Example 1 and 2?

Both logs same output: A B C D

Few things to observer

  • It doesn't matter if the promise is immediately resolved (Example 1) or took 100ms in (Example 2), the output remains the same. Because promises behaves asynchronous all the time.
  • We are calling p.then multiple times, i.e A promise is once resolved it has immutable value either resolved or rejected.
  • Why can't the output be A D B C?
// Step 1
p.then(function (val) {
  // Step 2
  console.log(val)
  p.then(function () {
    // Step 3
    console.log('D')
  })
  console.log('B')
})
Enter fullscreen mode Exit fullscreen mode

Promises are added to job queues in the Event loop, it has a tick which loops and executes any callback event queues scheduled. For every one such tick or end of one async loop, it checks for the job queues and runs execute any callbacks.

In the above example inside Step 2, JS engine starts printing first console and adds p.then to job queue and prints B. And finally job queue picks up after the async loop and executes Step 3.

Top comments (2)

Collapse
 
_bkeren profile image
''

what about the promise "then" that prints 'C'? How is guaranteed to run before promise callback that prints 'B'?

Collapse
 
yo08315171 profile image
Yo

Event loop visualiser I think this visualisation of event loop would help us to understand why B always prints before C.

p.then callbacks of B and C are parallel, so B's callback takes precedence as event loop uses queue as a data structure for Task and Job queues.

Execution steps are as follows

  • Within p.then (B)
    • Prints A (resolved value from promise)
    • Ignore p.then (console.log(D)) as it is not sequential for time being
    • Prints B
  • Within p.then (C)
    • Prints C
  • Within p.then (D)
    • Prints D I hope that answers your question, I found it difficult to explain this way. Will update if I get a better way of explaining.