Order of processing microtasks in JavaScript

66 Views Asked by At

I’m solving an event loop problem in Javascript and I can’t figure out why the output order is 2, 1, and not 1, 2.

f1();

Promise.resolve().then(() => {
  console.log(2);
});

async function f2() {
  return new Promise((resolve) => {
    resolve();
  });
}

async function f1() {
  f2().then(() => {
    console.log(1);
  });
}

Let me tell you my reasoning:

  1. As far as I understand, the first task in call stask will be f1. This function is asynchronous and returns a promise.

  2. f1 is being executed.

  3. Inside f1 there is a call to f2, which returns a promise and immediately resolves it. Therefore, a callback in "then" containing console.log(1) is added to the microtask queue.

  4. There is one more task left on the call stack - Promise.resolve(). Here a callback in "then" containing console.log(2) also ends up in the microtask queue.

  5. The call stack is empty, which means the event loop executes tasks from the microtask queue in order - 1, 2.

At some of these steps I was definitely mistaken in my reasoning. I will be very grateful if anyone helps me!)

0

There are 0 best solutions below