console.log('*********************************************************')
setTimeout(() => {
console.log("主要是看宏任务什么时候执行")
}, 0);
var p1 = new Promise((res, rej) => {
res('promise 1 的 then1')
}).then(res => {
console.log(res)
// promise 1 的子promise1-2
new Promise((res, rej) => {
// setTimeout(() => {
// res('新的 promise')
// }, 1000);
res('promise 1 的子promise1-2 的 then1') // 这里又给微任务队列注册了一个队列
}).then(v => {
console.log(v)
return 'promise1-2 的 then2 '
}).then(v => {
console.log(v)
})
return 'prmise 1 的 then2'
}).then(v => {
console.log(v)
})
var p2 = new Promise((res, rej) => {
res('promise 2 的 then 1')
}).then(res => {
console.log(res)
return 'promise 2 的 then 2'
}).then(v => {
console.log(v)
})
分析:
这个例子其实说明了 promise决议后 如果有then,就会把then再临时加入微任务队列末尾,继续执行
顺序执行代码 一开始 只有promise1,promise2 完成决议判读 所以 微任务队列 只有 promise1 promise2,
执行 promise 1 的 then1 时候, 产生新的Promise1-2,并且完成决议,所以微任务队列末尾加入promise1-2 的 then1,
截至执行了 return, 此时promise1 完成决议,又把 promise 1 的 then2 加入末尾队列,
=== 》 此时只是 打印了 promise 1 的 then1,
接着执行 微任务队列, ==》打印 promise 2 的 then 1,又把promise 2 的 then 2 加入微任务队列,
执行微任务队列里的 promise1-2 时候,==》打印 promise 1 的子promise1-2 的 then1,
又把 promise 1 的 子promise1-2 的 then2 加入微任务队列,接着打印==》 promise1的 then2 ,
此时并不产生新的决议,所以没有新的promise加入微任务队列,接着执行 promise 2 的 then 2 打印==》promise 2 的 then 2,接着执行 promise1-2 的 then2 打印 ==》 promise1-2 的 then2
到此时 微任务全部执行完毕i,开始执行宏认为队列,打印 ==》主要是看宏任务什么时候执行
打印顺序完整为:
promise 1 的 then1
promise 2 的 then 1
promise 1 的子promise1-2 的 then1
prmise 1 的 then2
promise 2 的 then 2
promise1-2 的 then2
主要是看宏任务什么时候执行
微任务队列 完整顺序:
promise1(promise 1 的 then1) ==》promise2( promise 2 的 then 1) ==》 promise1-2 的 then1 ==》
promise 1 的 then2 ==》 promise 2 的 then 2 ==》 promise1-2 的 then2