Web Development
Photo
click to show
click to show
The Microtask Queue
Promises don't execute immediately after they resolve. They wait their turn.
The Microtask Queue is a queue that stores callbacks from resolved Promises before they're executed.
Consider:
console.log("A");
Promise.resolve().then(() => console.log("B"));
console.log("C");
The output is:
A
C
B
Even though the Promise resolves immediately, its callback is placed into the Microtask Queue.
JavaScript finishes the current execution first. Only then does it process queued microtasks.
This is the reason why Promise callbacks always run after synchronous code, even when no network request is involved.
1 · 388 ·