写在前:js是单线程的(从上到下执行),同步任务进入主线程,异步任务进入队列。
宏任务:
script(整体代码)
setTimeout
setInterval
I/O
UI交互事件
postMessage
MessageChannel
setImmediate(Node.js 环境)
微任务:
Promise.then (await后面的代码 等于 .then()里面的代码)
Object.observe
MutaionObserver
process.nextTick(Node.js 环境)
看下面一段代码:分析输出结果(你可以先把填充的数字修改成空,重新填充以便更好的理解)
console.log('a');
async function async1() {
console.log('2');
await async2();
console.log('8');
new Promise(function(resolve) {
console.log('9');
resolve();
}).then(function() {
console.log('11');
});
}
async function async2() {
console.log('3');
setTimeout(function() {
console.log('13');
}, 0)
new Promise(function(resolve) {
console.log('4');
resolve();
}).then(function() {
console.log('7');
});
}
console.log('1');
setTimeout(function() {
console.log('12');
}, 0)
async1();
new Promise(function(resolve) {
console.log('5');
resolve();
}).then(function() {
console.log('10');
});
console.log('6')
//a,1,2.......13
注意:
new Promise(function(r) {
console.log('1');
r();
})
async function aa() {
console.log('2');
await cc();
console.log('3');
}
注意:在.then() 之前的代码为同步
await cc() 为同步
规则:同步进入主线程,异步进入队列,异步中微任务优先于宏任务
注:微任务中.nextTick 优先于.then()执行
注:异步中微任务优先,.then() 优先于 setTimeout
最后:如果有便捷的理解过程可以留言,此文若有问题请留言以便修正