Node.js
Microtask
Learn microtasks and nextTick.
Microtask
Microtasks are small jobs that run between event loop phases. There are two kinds: process.nextTick and Promise callbacks. nextTick always runs before Promises.
A microtaskOrder(tasks) function models this priority: it turns the array ['nextTick', 'promise'] into the string 'nextTick -> promise'. In real Node.js the microtask queue is drained after each phase; the nextTick queue first, then the promise queue. So if process.nextTick(() => ...) and Promise.resolve().then(() => ...) are used together, nextTick runs first. The output is nextTick -> promise; this order always holds.
nextTick priority
We can model the microtask order with a function. microtaskOrder(['nextTick', 'promise']) returns 'nextTick -> promise'. This shows with a fixed string that nextTick always runs first.
The function is simple: return tasks.join(' -> '). The tasks array is already in the right order (nextTick first). The output is nextTick -> promise. In real Node.js this order comes from how the microtask queue is drained: the nextTick queue is fully emptied, then the promise queue. This model visualizes the order with a deterministic string; no timer uncertainty. The fact that nextTick runs before Promise is thus pinned down.
Exercise Write the microtask order
Write function microtaskOrder(tasks). Return tasks.join(' -> '). Print console.log(microtaskOrder(['nextTick', 'promise'])).
Show example solution
function microtaskOrder(tasks) {
return tasks.join(' -> ');
}
console.log(microtaskOrder(['nextTick', 'promise']));
Test yourself
-
Match each concept to its description
- process.nextTick
- Microtask that runs first
- Promise.then
- Microtask that runs after nextTick
- Microtask
- Runs between phases
- Phase
- Event loop step
-
Complete the join call
return tasks.____(' -> ');
Show answer
return tasks.join(' -> ');
-
If nextTick and Promise are used together, which runs first?
process.nextTick(() => {});
Promise.resolve().then(() => {});
- At the same time
- Rastgele
- Promise
- nextTick
Show answer
nextTick — nextTick always runs before Promise.
Next lesson: Timers queue