一、关键词解析:
微任务:promise.then、async/await、process.nextTick、MutationObserve
宏任务:I/O、setTimeout、setInterval、setImmediate、requestAnimationFrame
二、执行原则:
先执行同步再执行异步,异步遇到微任务,先执行微任务,执行完后如果没有微任务,就执行下一个宏任务,如果有微任务,就按顺序一个一个执行微任务
三、例子:
Example1:
Promise.resolve().then(() => {
console.log(0);
return Promise.resolve(4);
}).then((res) => {
console.log(res)
})
Promise.resolve().then(() => {
console.log(1);
}).then(() => {
console.log(2);
}).then(() => {
console.log(3);
}).then(() => {
console.log(5);
}).then(() =>{
console.log(6);
})
// 执行结果:0,1,4,2,3,5,6
Example2:
console.log('iop');
new Promise((resolve, reject) => {
console.log('promise-1');
setTimeout(() => {
console.log('promise-timeeout');
}, 0)
process.nextTick(function () {
console.log('promise---process.nextTick-1');
})
resolve('222')
}).then((res) => {
setTimeout(() => {
console.log('promise-then-timeout');
}, 0)
console.log('promise-then');
process.nextTick(function () {
console.log('promise.then---process.nextTick-1');
})
})
console.log('iop3333');
setTimeout(() => {
console.log('timeout-222');
}, 0)
process.nextTick(function () {
console.log('process.nextTick-1');
})
// 执行结果:
/**
iop
promise-1
iop3333
promise---process.nextTick-1
process.nextTick-1
promise-then
promise.then---process.nextTick-1
promise-timeeout
timeout-222
promise-then-timeout
*/
Example3:
console.log(1)
setTimeout(function() {
console.log(2)
new Promise(function(resolve) {
console.log(3)
resolve()
}).then(function() {
console.log(4)
})
})
new Promise(function(resolve) {
console.log(5)
resolve()
}).then(function() {
console.log(6)
})
setTimeout(function() {
console.log(7)
new Promise(function(resolve) {
console.log(8)
resolve()
}).then(function() {
console.log(9)
})
})
console.log(10)
// 执行结果:1,5,10,6,2,3,4,7,8,9