I am a beginner in JS and While going through Event Loop and Promises
, I came across the below example at mdn
.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
wait().then(() => console.log(4));
Promise.resolve().then(() => console.log(2)).then(() => console.log(3));
console.log(1); // 1, 2, 3, 4
Shouldn't the O/P be 1,4,2,3
?
These are the steps, which according to my understanding should have happened
log(1) and then empty the MicroTask Q in the FIFO order. What am I getting wrong here, please explain
The wait
function's promise resolves only after the setTimeout
finishes - after a macrotask (a few milliseconds) In contrast, the Promise.resolve
gets put onto the microtask queue, which will run first (often a millisecond or less). After the console.log(1)
line runs, you'll have the following:
Microtask queue: .then(() => console.log(2)).then(() => console.log(3));
Macrotask queue: resolve
(due to the setTimeout
)
Microtask queue runs first, so 2
gets logged, then the next .then
gets put onto the microtask queue, and 3
gets logged. Finally, the setTimeout
macrotask runs, resolving the wait
Promise, putting another .then
onto the microtask queue, and shortly causing 4
to be logged.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.