Just-Now-QA icon indicating copy to clipboard operation
Just-Now-QA copied to clipboard

微任务/宏任务 执行顺序 event loop

Open mrrs878 opened this issue 3 years ago • 1 comments

new Promise((resolve,reject)=>{
    console.log("1")
    resolve();
}).then(()=>{
    console.log("2")
    new Promise((resolve,reject)=>{
        console.log("3")
        resolve();
    }).then(()=>{
        console.log("4")
    }).then(() => {
        console.log("5")
    })
}).then((res)=>{
    console.log("6")
})

image

想问一下这个执行输出为什么6在5之前?

mrrs878 avatar Jun 22 '21 06:06 mrrs878

找到合理的解释了

高级进阶:深度揭秘 Promise 注册微任务和执行过程

new Promise((resolve,reject)=>{
    console.log("1")
    resolve();
}).then(()=>{
    // 外部第1个then
    console.log("2")
    new Promise((resolve,reject)=>{
        console.log("3")
        resolve();
    }).then(()=>{
        // 内部第1个then
        console.log("4")
    }).then(() => {
        // 内部第2个then
        console.log("5")
    })
}).then((res)=>{
    // 外部第2个then
    console.log("6")
})

简单来讲就是then回调的注册需要上一个then里面的同步代码执行完毕

拿上面的代码来讲,当外部第1个then里的resovle()执行完毕后,该Promise的状态已经更改,会将内部第1个then回调添加(注册)到微任务队列中;内部第2个then由于上一个then回调没有执行完毕,因此不会注册。此时外部第1个then里的同步代码执行完毕,会注册外部第2个then回调

整理一下:then回调注册的顺序是:外部第1个then --> 内部第1个then --> 外部第2个then --> 内部第2个then

ps: 如果将外部第1个then里的new Promise(xxx)改为return new Promise(xxx)的话内部第2个then的注册将早于* 外部第2个then*

mrrs878 avatar Jun 22 '21 15:06 mrrs878