1

new Promise(resolve= > {
    console.log('promise1');
    resolve();
}).then(() = > {
    console.log('then11');
    // return
    new Promise(resolve= > {
        console.log('promise2');
        resolve();
    }).then(() = > {
        console.log('then21');
    }).then(() = > {
        console.log('then22');
    });
}).then(() = > {
    console.log('then12');
});
Copy the code

Results:

The basic model for event queue execution

Step by step:

First of all,

new Promise(resolve= > {
    console.log('promise1');
    resolve();
})
Copy the code

The executor function is executed synchronously, so output ‘promise1’

Then execute resolve() to synchronously change the state and value of the Promise. Then whether to set microtasks depends on the situation

If then is executed before resolve, resolve is asynchronous code. Then: execute. Then: execute. Then: execute. Then: execute.

If then is executed after resolve, if there is no save method, as in this example, resolve is synchronous and then is not executed at the time resolve is executed, then is executed later. Then the microtask is skipped without setting.

Then execute the.then() method,

.then(() = > {
    console.log('then11');
    // return
    new Promise(resolve= > {
        console.log('promise2');
        resolve();
    }).then(() = > {
        console.log('then21');
    }).then(() = > {
        console.log('then22');
    });
})
Copy the code

Execute.then() to first look at the state of the current instance.

If pendding, store this method, execute resolve whenever possible, and use the resolve microtask to execute the then callback function.

If the current instance is in a successful or failed state, resolve has been run synchronously, as in this example. If you determine the state, you know which methods of then are executed. Then set the callback function in.then to a microtask that waits for synchronization to end

So we treat the then callback as microtask 1, put it into the microtask queue, and execute it when the synchronization ends

The second then is executed

.then(() = > {
    console.log('then12');
})
Copy the code

The first then() microtask 1 has not been executed until the synchronization has finished, so this method is saved as a microtask, which we call microtask 2. Microtask 2 needs to wait for microtask 1 to determine its status before executing.

After synchronization is complete, microtask 1 is executed

() = > {console.log('then11');
    new Promise(resolve= > {
        console.log('promise2');
        resolve();
    }).then(() = > {
        console.log('then21');
    }).then(() = > {
        console.log('then22');
    });
}
Copy the code

Output ‘then11’

 new Promise(resolve= > {
        console.log('promise2');
        resolve();
    })
Copy the code

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # At this time, microtask 1 has not been completed and has not been executed to the bottom, so microtask 3 takes precedence over microtask 2

// Microtask 3() = > {console.log('then21');
    }
Copy the code

Then go on.

.then(() = > {
        console.log('then22');
    })
Copy the code

This then creates a microtask 4 that is not known to be executed until microtask 3 is completed.

And then you finish microtask 1, you finish microtask 1, you can decide the last onethenAt this time, microtask 2 should be executed immediately. Microtask 2 has a higher priority than microtask 4

If there is a task in the task queue, the first person who knows it is executable (who arrives first) executes it first

Perform to the console. The log (‘ promise2 ‘); resolve(); Then () will not execute task 3 in the first then, and will be placed on the microtask queue. When task 23 is completed, microtask 43 will be created and placed on the microtask queue. When task 1 is completed, microtask 43 will be created and placed on the task queue. Task 2 already placed in the task queue is executed.

If you change it to this:

new Promise(resolve= > {
    console.log('promise1');
    resolve();
}).then(() = > {
    console.log('then11');
    return new Promise(resolve= > {
        console.log('promise2');
        resolve();
    }).then(() = > {
        console.log('then21');
    }).then(() = > {
        console.log('then22');
    });
}).then(() = > {
    console.log('then12');
});
Copy the code

2

setTimeout(() = > {
    console.log(1);
}, 20);
console.log(2);
setTimeout(() = > {
    console.log(3);
}, 10);
console.log(4);
console.time('AA');
for (let i = 0; i < 90000000; i++) {
    // do soming
}
console.timeEnd('AA'); / / = > AA: around 70 ms
console.log(5);
setTimeout(() = > {
    console.log(6);
}, 8);
console.log(7);
setTimeout(() = > {
    console.log(8);
}, 15);
console.log(9);
Copy the code

70ms has passed by the time the synchronization code is executed, and the time for the above two macro tasks has expired. Therefore, when the synchronization code is executed, the above two macro tasks will be executed immediately, and then the next two new macro tasks will be executed after 8 and 15 milliseconds.

After the synchronization ends:

SetTimeout (() => {},0), setTimeout(() => {}) : The timer is set to 0 or not written, and is not executed immediately. Browsers have a fastest processing response time (Google 5-7ms). Ie10-17ms), it takes about 5-7ms to write a 0, so it is also asynchronous

Js processing speed is very fast, the interval processing of two adjacent synchronous codes is only about 0.01ms

3

async function async1() {
    console.log('async1 start');
    await async2();
    console.log('async1 end');
}
async function async2() {
    console.log('async2');
}
console.log('script start');
setTimeout(function() {
    console.log('setTimeout');
}, 0)
async1();
new Promise(function(resolve) {
    console.log('promise1');
    resolve();
}).then(function() {
    console.log('promise2');
});
console.log('script end');
Copy the code

The async1() function is executed as follows

Note that the execution is completeawait async2();The following code is created as microtask 2 and the status is already known, so it can be executed as soon as the synchronization is complete

Continue to run as follows:performthenSince the status is already known, add microtask 3 to the microtask queue and execute it immediately after the synchronization

4

let body = document.body;
body.addEventListener('click'.function () {
    Promise.resolve().then(() = > {
        console.log(1);
    });
    console.log(2);
});
body.addEventListener('click'.function () {
    Promise.resolve().then(() = > {
        console.log(3);
    });
    console.log(4);
});
Copy the code

Code execution, add two callback functions as macro tasks, and clickbody, 2,4 are synchronous tasks, and 1,3 are micro tasks in the two macro tasks. To complete a macro task before the next macro task, a macro task before the completion of their own internal micro task, so 21 first, 43 after

5

console.log('start');
let intervalId;
Promise.resolve().then(() = > {
    console.log('p1');
}).then(() = > {
    console.log('p2');
});
setTimeout(() = > {
    Promise.resolve().then(() = > {
        console.log('p3');
    }).then(() = > {
        console.log('p4');
    });
    intervalId = setInterval(() = > {
        console.log('interval');
    }, 3000);
    console.log('timeout1');
}, 0);
Copy the code

Distinguish between macro and micro tasks and synchronize tasks

6

setTimeout(() = > {
    console.log('a');
});
Promise.resolve().then(() = > {
    console.log('b');
}).then(() = > {
    return Promise.resolve('c').then(data= > {
        setTimeout(() = > {
            console.log('d')});console.log('f');
        return data;
    });
}).then(data= > {
    console.log(data);
});
Copy the code

B microtask, F synchronous task, and finally wait for return to execute the last THEN, complete all the microtasks, and then execute two macro tasks.

7

function func1() {
    console.log('func1 start');
    return new Promise(resolve= > {
        resolve('OK');
    });
}
function func2() {
    console.log('func2 start');
    return new Promise(resolve= > {
        setTimeout(() = > {
            resolve('OK');
        }, 10);
    });
}
console.log(1);
setTimeout(async() = > {console.log(2);
    await func1();
    console.log(3);
}, 20);
for (let i = 0; i < 90000000; i++) {} // The loop takes about 80MS
console.log(4);
func1().then(result= > {
    console.log(5);
});
func2().then(result= > {
    console.log(6);
});
setTimeout(() = > {
    console.log(7);
}, 0);
console.log(8);
Copy the code