自己给自己出道题,直接上代码
new Promise((resolve) => {
resolve()
}).then(() => { // then1
console.log(1)
Promise.resolve()
.then(() => { // then2
console.log(2)
})
.then(() => { // then3
console.log(3)
Promise.resolve()
.then(() => { // then4
console.log(4)
}).then(() => { // then5
console.log(5)
})
}).then(() => { // then6
console.log(6)
})
}).then(() => { // then7
console.log(7)
}).then(() => { // then8
console.log(8)
Promise.resolve()
.then(() => { // then9
console.log(9)
}).then(() => { // then10
console.log(10)
})
}).then(() => { // then11
console.log(11)
})
执行过程如下
// 微任务队列 先进先出 入栈: ->[] 出栈: then ->
// 注意点:then中的同步代码执行完毕后 才会继续链式调用,将后面的then继续放入队列中
// -> [then1]
// then1 -> 执行同步代码 打印1 将then2放入队列 then1中的同步代码执行完毕 将then1后的then7放入队列
// -> [then7,then2]
// then2 -> 执行同步代码 打印2 then2中的同步代码执行完毕 将then2后的then3放入队列
// -> [then3, then7]
// then7 -> 执行同步代码 打印7 then7中的同步代码执行完毕 将then8放入队列
// -> [then8, then3]
// then3 -> 执行同步代码 打印3 定义了一个新的promise 将then4放入队列 then3中的同步代码执行完毕 将then3后面的then6放入队列中
// -> [then6, then4, then8]
// then8 -> 执行同步代码 打印8 定义了一个新的promise 将then9放入队列 then8中的同步代码执行完毕 将then8后面的then11放入队列中
// -> [then11, then9, then6, then4]
// then4 -> 执行同步代码 打印4 then4中的同步代码执行完毕 将then5放入队列
// -> [then5, then11, then9, then6]
// then6 -> 执行同步代码 打印6 then6中的同步代码执行完毕
// then9 -> 执行同步代码 打印9 then9中的同步代码执行完毕 将then10放入队列中
// -> [then10, then5, then11]
// -> then11 -> 执行同步代码 打印11 then11中的同步代码执行完毕
// -> then5 -> 执行同步代码 打印5 then5中的同步代码执行完毕
// -> then10 -> 执行同步代码 打印10 then10中的同步代码执行完毕
执行结果如下
> 1
> 2
> 7
> 3
> 8
> 4
> 6
> 9
> 11
> 5
> 10