We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Microtask Queue

Okay so there's one more queue to be aware of: the microtask queue.

Just like the task queue, the microtask queue is a mechanism for scheduling tasks to be executed later. But it operates under different rules and is used for different purposes. The nature of microtasks is that they represent smaller, shorter-lived operations compared to tasks in the task queue. And importantly, promises use the microtask queue to schedule their .then() and .catch() callbacks.

There are two important differences between the task queue and the microtask queue:

  • Order of Execution: All microtasks are executed before the next task in the task queue.
  • Addition of Microtasks: Microtasks can add more microtasks to the queue, and those will still execute before the next "macro" task.

So Do I Need to Care?

Well, usually... no. But sometimes yes. For the most part, you can think about promises and callbacks as just "asynchronous operations that will run later". You typically won't (and it's often a bad sign if you do) care about the exact order that their callbacks will run.

But I believe in learning stuff, so let's dive in. This example shows the difference between the "macro" (regular) task queue and the microtask queue:

function main() {
  console.log("main start");

  setTimeout(() => {
    console.log("macrotask 1 finished");
  }, 0);

  Promise.resolve()
    .then(() => {
      console.log("microtask 1 finished");
    })
    .then(() => {
      console.log("microtask 2 finished");
    });

  console.log("main end");
}

main();

It prints:

main start
main end
microtask 1 finished
microtask 2 finished
macrotask 1 finished

The important thing to note is simply that all the microtasks run before the next task in the task queue.

Assignment

Textio's analytics system isn't working. Fix the processAnalytics function by using a Promise to concatenate - Processing: ${data} to final analysis before it's finished.