Macro and micro-tasks and tasks ----- promise setTimeout priority

First, take a look at the concept:
①macro-Task (macro task): including the overall Code Script, the setTimeout, setInterval
②micro-Task (micro tasks): Promise, process.nextTick

Macro and micro task execution flow of tasks:
Here Insert Picture Description
implementation mechanisms: Macro executing the task will be to carry out micro-task, and all the micro-tasks.

new Promise(function(resolve){//promise里面的函数也是同步
    console.log(2)
    for( var i=0 ; i<10000 ; i++ ){
        i==9999 && resolve()
    }
    console.log(3)
}).then(function(){//异步操作
    console.log(4)
});
setTimeout(function(){
	console.log(1);//异步操作
},0);
console.log(5);//同步
//2
//3
//5
//4
//1

js single-threaded order is: first synchronize asynchronous, it is very important
① first encounter task script macro, script there are setTimeout and promise, to perform tasks setTimeout macro, micro and then perform the task promise;
after ②promise execute, then will be distributed the micro task; then will output: 2,3
③ console encountered immediate execution; then will output:. 5
④ overall macro task (task refers to a macro script tag) execution is completed, the next task is determined whether there is a micro, micro mission there then, execute; then will output: 4
⑤ok, the end of the first round of the event, second round, we just put into the event queue of setTimeout function to the macro task execution immediately; then will output: 1
⑥ end.

Published 89 original articles · won praise 5 · views 20000 +

Guess you like

Origin blog.csdn.net/me_never/article/details/102472565