首先执行顺序:同步任务->异步任务
异步任务又分为:宏任务与微任务。
所以整个顺序为:同步任务->微观任务->宏观任务
微观任务大概有Promise.then Object.observe MutationObserver process.nextTick(Node.js 环境)
宏观任务大概有script(整体代码) setTimeout setInterval I/O UI交互事件 postMessage MessageChannel setImmediate(Node.js 环境)
每当一个宏任务执行完之后,会检查是否有微任务,如果有,则会先执行所有微任务,再执行下一个宏任务。
题目一
setTimeout(function() {
console.log('1') // 宏任务
})
new Promise(function(resolve) {
console.log('2') // 同步任务
resolve()
}).then(function() {
console.log('3') // 微任务
})
console.log('4') // 同步任务
输出:2431
题目二
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')
})
})
首先执行同步任务 1 5
再执行resolve异步微观任务6;判断是否所有微观任务都执行完了,是->执行下一个宏任务。
setTimeout宏观任务:2,3同步任务,4异步微观任务。
下一个setTimeout宏观任务:同理7,8同步任务,9异步微观任务。
所以输出结果为156234789