JS event loop

setTimeout(() => { console.log(1) }, 1000)
new Promise(resolve => {
    setTimeout(() => { resolve(2) }, 1000)
}).then(data => {
    console.log(data); // then
});
console.log(3)

then

new Promise(resolve => {
    console.log("1");
    for(var i = 0; i < 1000; iPP) {
        i == 99 && resolve();
    }
    console.log("2");
}).then(function() {
    console.log("3");
})
console.log(4)
then1
Mar.10,2022

then is executed only when the last resolve is received, so the output result will be

according to your code.

3Jing 1 Jing 2

The output of

3 is not to mention that the result of
Promise is a console, of settimeout, so the effects of 1 and 2 are the same, and the output results are 1, 2

according to the order of execution.

there is no loop, setTimeout is a timing function, it means that it will be executed in a few seconds, promise is a promise, and the function after then is executed in the promise function after it is executed. You can judge the execution order according to this idea. The execution result can be executed once in the console to know that


event loop refers to a mechanism, which is divided into macro tasks and micro tasks. The above code starts to execute, encounter setTimeout will put the callback function into the macro task queue, encounter new Promise, will first execute the constructor method, that is, setTimeout (() = > {resolve (2)}, 1000) , also put the callback function into the macro task queue, and then execute console.log (3) , output 3, and then first execute the micro task queue, found that there is no task inside, the end. At this point, a cycle is complete. Then start the next loop, execute the code in the macro task, that is, console.log (1) , output 1, and then scan the micro task to find no, end. Then start the third loop to execute the macro task, that is, resolve (2) , which adds the then method, that is, console.log (data); , to the promise task source, and then executes the micro task, outputting 2.
so loop 3 times, output 3, output 1, 2


it's time to find out this article again
https://juejin.im/post/59e85e.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b308ba-2bd2c.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b308ba-2bd2c.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?