先看面试题
async function async1() {
console.log('async1 start');
await async2();
console.log('asnyc1 end');
}
async function async2() {
console.log('async2');
}
console.log('script start');
setTimeout(() => {
console.log('setTimeOut');
}, 0);
async1();
new Promise(function (reslove) {
console.log('promise1');
reslove();
}).then(function () {
console.log('promise2');
})
console.log('script end');
输出结果:
script start
async1 start
async2
promise1
script end
asnyc1 end
promise2
setTimeOut
大佬的文章:JS宏任务和微任务知识点相关
//主线程直接执行
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')
})
})
//微事件1
process.nextTick(function() {
console.log('6');
})
//主线程直接执行
new Promise(function(resolve) {
console.log('7');
resolve();
}).then(function() {
//微事件2
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')
})
})
JS宏任务和微任务
setTimeout(() => {
//执行后 回调一个宏事件
console.log('内层宏事件3')
}, 0)
console.log('外层宏事件1');
new Promise((resolve) => {
console.log('外层宏事件2');
resolve()
}).then(() => {
console.log('微事件1');
}).then(() => {
console.log('微事件2')
}}
打印结果
外层宏事件1
外层宏事件2
微事件1
微事件2
内层宏事件3
- 首先浏览器执行js进入第一个宏任务进入主线程,遇到setTimeout 分发到宏任务Event Queue中
- 遇到 console.log()直接执行输出 外层宏事件1
- 遇到Promise,new Promise直接执行 输出 外层宏事件2
- 执行then被分发到微任务Event Queue中
- 第一轮宏任务执行结束,开始执行微任务 打印‘微事件1’‘微事件2’
- 第一轮微任务执行完毕,执行第二轮宏事件,打印setTimeout里面内容‘内层宏事件3’
宏任务
# | 浏览器 | Node |
---|---|---|
setTimeout | √ | √ |
setInterval | √ | √ |
setImmediate | × | √ |
requestAnimationFrame | √ | × |
微任务
# | 浏览器 | Node |
---|---|---|
process.nextTick | × | √ |
MutationObserver | √ | × |
Promise.then catch finally | √ | √ |
宏 2
宏 4
微 3 5
宏 9
宏 10 11
微 12
1 7
微 6 8
176824359101112