promise-then执行顺序问题

以下代码,执行会输出什么

Promise.resolve().then(() => {
    console.log(0)
    return Promise.resolve(4)
}).then((res) => {
    console.log(res)
})

Promise.resolve().then(() => {
    console.log(1)
}).then(() => {
    console.log(2)
}).then(() => {
    console.log(3)
}).then(() => {
    console.log(5)
}).then(() =>{
    console.log(6)
})


// 0,1,2,3,4,5,6

then 交替执行

如果有多个 fulfilled 状态的 promise 实例,同时执行 then 链式调用,

then 会交替调用

这是编译器的优化,防止一个 promise 持续占据事件

Promise.resolve().then(() => {
    console.log(1)
}).then(() => {
    console.log(2)
}).then(() => {
    console.log(3)
}).then(() => {
    console.log(4)
})

Promise.resolve().then(() => {
    console.log(10)
}).then(() => {
    console.log(20)
}).then(() => {
    console.log(30)
}).then(() => {
    console.log(40)
})

Promise.resol

猜你喜欢

转载自blog.csdn.net/m0_38066007/article/details/124990766
今日推荐