1

Why does google chrome display 2 in the console, and then 1?

Promise.resolve().then(function() {
  Promise.resolve().then(function() {
    console.log('1');
  });
});


Promise.resolve().then(function() {
  console.log('2');
});
Nikita
  • 39
  • 4
  • 3
    What else would you expect and why? – Konrad Apr 26 '23 at 09:38
  • I expect the first 1 (since this is the second micro-task in the queue, after the first Promise.resolve.then()) – Nikita Apr 26 '23 at 09:42
  • It's the third microtask. It is added to the queue after the first one finishes which is after the second one is added – Konrad Apr 26 '23 at 09:43
  • also [What is the order of execution in JavaScript promises?](https://stackoverflow.com/questions/36870467/what-is-the-order-of-execution-in-javascript-promises) – pilchard Apr 26 '23 at 10:00

1 Answers1

2

This is because of the way promises and microtasks are handled in java script when a promise is reslved the callback function attached to it is queued as a microtask which is a unit of work that is scheduled to execute after the curent task i e the current function has completed in your code you have two promises that are resolved and have callback functions atached to them the first promise resolves and its callback function is queued as a microtask then the second promise resolves and its callback function is also queued as a microtask since both microtasks are queued at the same time the order in which they are excuted depends on the browser s implementation of the event loop in google chrome the microtask queue is implemented as a fifo first in first out queue which means that the first microtask that was queued i e the one from the first promise will be executed before the second micrtask therefore when you run this code in google chrome you will see the output 2 printed first followed by 1 the output 2 is printed immediately when the second promise is resolved while the output 1 is printed after the first promise s callback function is executed as a microtask note that the order in which microtasks are executed is not guaranteed by the java script specificaion and may vary across browsers so it s always a good practice to avoid relying on the order of execution of microtasks and write code that is independent of the execution order

Drake
  • 64
  • 2