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')
})
})
答案: 1、7、6、8、2、4、9、11、3、5、10、12
解析: 先同步执行代码,如果有异步的放到异步队列里面,异步队列又分 微任务 和 宏任务。
先执行微任务,当前微任务执行完毕-》执行宏任务 =》 当前宏任务执行完,看有没有剩下的微任务,再执行完所有的微任务,再执行下一个宏任务。
言简意赅,凑合看吧。
同步-》微任务-》宏任务 -》微任务
这个是讲js单线程异步概念的链接如果想了解的可以看这个
晚上再补个图,下班。