The original address: https://github.com/lzlu/Blog/issues/7

This article has nothing to do, but provides a solution to an interview question.

This question came up in the interview before, and I didn’t answer it correctly. Although this topic seems to have no practical significance for writing code, it is my lack of in-depth understanding of THE JS implementation mechanism.

Take this problem to share with you some ideas to solve the problem. JS execution mechanism is not enough to understand the recommendations of the first read this article this time, thoroughly understand JavaScript execution mechanism – nuggets, and then eat.

So without further ado, sauerkraut, no, question.

const first = (a)= > (new Promise((resolve,reject) = >{
    console.log(3);
    let p = new Promise((resolve, reject) = >{
         console.log(7);
        setTimeout((a)= >{
           console.log(5);
           resolve(6); 
        },0)
        resolve(1);
    }); 
    resolve(2);
    p.then((arg) = >{
        console.log(arg);
    });

}));

first().then((arg) = >{
    console.log(arg);
});
console.log(4);
Copy the code

The first event loop

First execute the macro task, the main script, new Promise immediately execute, print [3], execute the new Promise operation p, print [7], find setTimeout, put the callback into the Event Queue of the next task, then of P, let’s call then1, Put it in the microtask queue, find the then of first, called then2, put it in the microtask queue. Execute console.log(4), output [4], and the macro task is finished.

Then execute the micro task, execute then1, output [1], execute then2, output [2]. This is the end of the first event loop. Start the second round.

Second cycle of events

First execute the callback of setTimeout in the macro task, and output [5]. The resovle doesn’t work because once the state of p changes, it doesn’t change. So the final output order is 3, 7, 4, 1, 2, 5.

conclusion

Knowing the JavaScript execution mechanism, and knowing that the Promise constructor executes immediately, this topic should be fairly straightforward.