区别
- 宿主环境(window/global)提供的叫宏任务,由语言标准(es6)提供的叫微任务
执行顺序
- 宏任务 -> over -> 微任务队列 -> 宏任务
vue.nextTick
1、声明macroTask, macroToask, callbasks, useMacroTask等,
2、各种环境侦测下建立宏任务与微任务
第一轮侦测:
a、先检查是否存在setImmediate,有则建立宏任务
b、否则检查是否存在MessageChannel,有则建立宏任务
c、否则使用setTimeout建立宏任务
第二轮侦测:
a、检查是否存在promise,有则建立微任务
b、否则微任务等于宏任务.
3、暴露withMacroTask ,可以往宏任务推入回调
4、暴露nextTick:可以将回调推入微/宏任务等待执行。
例子
console.log('1');
setTimeout(function() {
console.log('2');
process.nextTick(function() {
console.log('3');
})
new Promise(function(resolve) {
console.log('4');
resolve();
}).then(function() {
console.log('5')
})
})
process.nextTick(function() {
console.log('6');
})
new Promise(function(resolve) {
console.log('7');
resolve();
}).then(function() {
console.log('8')
})
setTimeout(function() {
console.log('9');
process.nextTick(function() {
console.log('10');
})
new Promise(function(resolve) {
console.log('11');
resolve();
}).then(function() {
console.log('12')
})
})