// 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');
});
// 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');
});
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')
})
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)
what about the promise "then" that prints 'C'? How is guaranteed to run before promise callback that prints 'B'?
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