0

I was searching on a website and came across this question: Control unit. What follows here: Promise.resolve().then(() => setTimeout(() => console.log(4))); Is Promise = microtasks or setTimeout = macrotasks

console.log(1);

setTimeout(() => console.log(2));

Promise.resolve().then(() => console.log(3));

Promise.resolve().then(() => setTimeout(() => console.log(4)));

Promise.resolve().then(() => console.log(5));

setTimeout(() => console.log(6));

console.log(7);

The console output is: 1 7 3 5 2 6 4 Why is 6 executed before 4? I want to know why, advise me, what do I lack in order not to know something like that, what else should I learn?

I expected the console output to be: 1 7 3 5 2 4 6

  • I suppose the timeouts run in the order they are set – user253751 May 10 '23 at 15:56
  • Here is a simple explanation, if we right down each section and place a M or T or nothing next to number,.. `T = normal Task, M = microtask` `1 2T 3M 4MT 5M 6T 7` Now all not (M or T, MT) get executed -> `1 7`, next all M `3 5` next `T` `2 6`, and then lastly MT `4` as event loop goes MicroTasks / Task / MircoTasks / Task..etc.. – Keith May 10 '23 at 16:09

0 Answers0