JS execution order problem, Promise operation order problem

function f() {
  console.log("A");
  setTimeout(() => console.log("F"))
  new Promise((resolve, reject) => {
    console.log("B");
    resolve();
    console.log("C");
  }).then(() => console.log("E"));
  console.log("D");
}
f();

output result is

A
B
C
D
E
F

setTimeout is easier to understand, which is actually Event Loop , but Promise is not well understood. Can anyone explain how Promise works inside? Why E and then F?

Dec.03,2021

Promise and setTimeout enter different queues. Suppose queue An of Promise , queue B of setTimeout is higher than B, and only after An executes, B will be executed. When new Promise is executed, because it is followed by then , the callback of the following then will be pushed into A, and then the callback will be pushed to A

you can take a look at the following article. The demonstration is very vivid
Tasks, microtasks, queues and schedules

. < H2 > add < / H2 >

the queue An above is microtask , and queue B is macrotask . They are all asynchronous tasks. The difference is that microtask takes precedence over macrotask , and in each time cycle, macrotask will extract only one execution, while microtask will always extract until microtask queue is empty. If then "E" is followed by then , then the following then will be executed, and finally setTimeout
. For more details, please see the following article
understand macrotask and microtask in JavaScript

. < H2 > add again < / H2 >

later, a problem was found during the test. The following code is inconsistent in node and chrome .

  detailed explanation of the operating mechanism of JavaScript: let's talk about Event Loop  

					
Menu