Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
mrrs878 opened this issue Jun 22, 2021 · 1 comment
Open

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

mrrs878 opened this issue Jun 22, 2021 · 1 comment

Comments

@mrrs878
Copy link

mrrs878 commented Jun 22, 2021

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
Copy link
Author

mrrs878 commented Jun 22, 2021

找到合理的解释了

高级进阶:深度揭秘 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*

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants