There are always tricky interview questions about the cycle of events, but as long as you grasp the essence of it, the tricky questions will be easily solved. Let’s explore how it works

First, take a look at a piece of code

new Promise(resolve= > {
    console.log(1);
    resolve(3);
}).then(num= > {
    console.log(num)
});
console.log(2)

// The output sequence is 123
Copy the code

First: new Promise(()=>{}).then(() =>{}) Step 2: Resolve (3) Promise after resolve, the state will change from pengding to depressing. Then the then method of the promise object will be called, but note that the method here is an asynchronous microtask. Step 3: console.log(2) is the synchronization task. Therefore, the final output order is 123.

If you add a promise to a promise:

new Promise(resolve= > {
    console.log(1);
    // resolve(3);
    Promise.resolve().then(() = > console.log(4))
}).then(num= > {
    console.log(num)
});
console.log(2)

// The output order is 124
Copy the code

Without resolve(), the state of a promise remains pending and does not start then(). In fact, there are many points of knowledge not mentioned, will continue to update this article