CodeBlanks Logo Icon CodeBlanks

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.

Practice Write the microtask order

Write function microtaskOrder(tasks). Return tasks.join(' -> '). Print console.log(microtaskOrder(['nextTick', 'promise'])).

Starter code

index.js
// Write a microtaskOrder function
// Join the task array with ' -> '
// Call with ['nextTick', 'promise'], print
// write here

Sample solution

index.js
function microtaskOrder(tasks) {
  return tasks.join(' -> ');
}
console.log(microtaskOrder(['nextTick', 'promise']));

Expected output

nextTick -> promise

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each concept to its description

Term Meaning
process.nextTick Microtask that runs first
Promise.then Microtask that runs after nextTick
Microtask Runs between phases
Phase Event loop step

2 Complete the join call

Question
return tasks.____(' -> ');
Answer
return tasks.join(' -> ');

Explanation: join combines the array into a string.

3 If nextTick and Promise are used together, which runs first?

index.js
process.nextTick(() => {});
Promise.resolve().then(() => {});
  • At the same time
  • Rastgele
  • Promise
  • nextTick Correct answer

Explanation: nextTick always runs before Promise.

All lessons in Expert