首先看一段关于Promise的代码
console.log('start here')
new Promise((resolve,reject) => {
console.log('first promise constructor')
resolve()
}).then(() => {
console.log('first promise then')
return new Promise((resolve,reject) => {
console.log('second promise')
resolve()
}).then(() => {
console.log('second promise then')
})
}).then(() => {
console.log('auther first promise then')
})
console.log('end here')
分析代码:
start thenPromise构造函数,同步代码,输出first promise constructor,同时将第一处Promise的then方法完成处理逻辑放入任务队列end herefirst promise then和second promisethen方法中返回一个Promise时,second promise then的then方法进入任务队列,由于主线程中没有其他任务,因此会执行then方法,输出second promise thenauther first promise then任务队列中的异步任务其实又分为宏任务、微任务,也就是说宏任务和微任务虽然都是异步任务,都在任务队列,但是他们在不同的队列中。
宏任务:
微任务:
console.log('start here')
const foo = () => (new Promise((resolve, reject) => {
console.log('first promise constructor')
let promise1 = new Promise((resolve,reject) => {
console.log('second promise constructor')
setTimeout(() => {
console.log('setTimeout here')
resolve()
},0)
resolve('promise1')
})
resolve('promise0')
promise1.then(arg => console.log(arg))
}))
foo().then(arg => {
console.log(arg)
})
console.log('end here')
宏任务队列:setTimeout
微任务队列:promise1.then,foo().then
输出结果:
“start here”
“first promise constructor”
“second promise constructor”
“end here”
“promise1”
“promise0”
“setTimeout here”
结论:
每次主线程执行栈为空的时候,引擎都会优先处理微任务队列,处理完后,再处理宏任务