What could be execution order
Case1: Code in main module (Normal case)
- setTimeout(() => console.log("timeout"), 0);
- setImmediate(() => console.log("immediate"));
- Promise.resolve().then(() => console.log("promise"));
- process.nextTick(() => console.log("nextTick"));
Output:
- nextTick
- promise
- timeout
- immediate
Explanation:
Microtasks run after every phase, before moving to next phase.
Microtasks are executed immediately after the current operation, before the event loop proceeds to the next phase
Execution priority:
-
process.nextTick -
Promises (
.then) -
Then event loop phases
- nextTick will go in process.nextTick() queue
- Promise will go in Promise microtask queue
Based on above given priority nextTick priority next click is always on top and then promise.
process.nextTick (nextTick)- Promises (
.then) (Promise) - Event Loop (setimmediate, settimeout, setinterval)
Event loop phases in order
1. Timers
2. Pending Callbacks
3. Idle, Prepare (internal)
4. Poll (MOST IMPORTANT)
5. Check
6. Close Callbacks
2. Pending Callbacks
3. Idle, Prepare (internal)
4. Poll (MOST IMPORTANT)
5. Check
6. Close Callbacks
settimeout, setinterval executes in Timers phase
Setimmediate executes in Check phase
This is how below order comes in output
- nextTick
- promise
- timeout
- immediate
Case2: The callback runs inside the Poll phase (I/O phase)8 (Special case)
const fs = require("fs");
fs.readFile(__filename, () => {setTimeout(() => console.log("timeout"), 0);
setImmediate(() => console.log("immediate"));
Promise.resolve().then(() => console.log("promise"));
process.nextTick(() => console.log("nextTick"));
});
Output:
- nextTick
- promise
- immediate
- timeout
immediate and timeout sequence changed compare to normal case
Explanation:
Above code will run inside the Poll phase (I/O phase) because its I/O file read operation.
All I/O operations/API calls goes in Poll phase
All I/O operations/API calls goes in Poll phase
Inside that callback, we schedule:
| API | Goes to |
|---|---|
setTimeout | Timers queue |
setImmediate | Check queue |
Promise.then | Microtask queue |
process.nextTick | NextTick queue |
nextTick registers in process.nextTick() queue
Promise registers in Promise microtask queue
Promise registers in Promise microtask queue
- next click is top priority so its at no.1
- microtask queue executed between each phase of Event Loop. currently execution is at poll phase as execution move to next phase first it will check and execute if anything in microtask queue, so Promise is at no.2
- next phase of event loop is check phase in which immediate get registered, so immediate is at no.3
- Execution finishes this cycle an re-iterate next cycle, in next cycle first phase is Timers, so timeout is at no.4
No comments:
Post a Comment