DEV Community

Discussion on: Titbits: Promises

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.