Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Preface 👀

Recently, a small partner in the group asked a Promise basic question, take it out to share!

We first know and understand the execution mechanism of event loop. This basic question is actually easy to explain

Event loop Its execution order:

  1. The entire script is initially executed as a macro task
  2. During the execution, the synchronized code is executed directly, the macro task enters the macro task queue, and the micro task enters the micro task queue
  3. Check the list of micro tasks after the current macro task is executed, and execute them successively until all the tasks are executed
  4. Performs rendering of the browser UI thread
  5. Check whether there are Web Worker tasks and execute them
  6. After executing the macro task of this round, return to 2 and repeat until the macro and microtask queues are empty

Microtasks include MutationObserver, promise.then () or Catch (), other technologies developed around Promise, such as the FETCH API, V8’s garbage collection process, and Node’s unique process.nexttick.

Macro tasks include: Script, setTimeout, setInterval, setImmediate, I/O, UI Rendering.

⚠️ One thing to note: at the beginning of all tasks, since the macro task includes script, the browser will execute one macro task first, and any delayed tasks you see during this process (such as setTimeout) will be put into the next macro task.

The title as follows

async function fn1() {
    console.log(1)}async function fn2() {
    console.log(2)}async function result() {
    await fn1()
    fn2()
    setTimeout(() = > {
       console.log(3);	
    });
    Promise.resolve().then(res= > console.log(4))
    console.log(5);
}

result()
console.log(6)
Promise.resolve().then(res= > console.log(7))
setTimeout(() = > {
    console.log(8); }); The Expected output:1 6 2 5 7 4 8 3
Copy the code

The illustration