Titbits: Promises
Yo
Posted on April 14, 2022
// 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.
💖 💪 🙅 🚩
Yo
Posted on April 14, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.