Giter Club home page Giter Club logo

Comments (1)

mrrs878 avatar mrrs878 commented on June 7, 2024

找到合理的解释了

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

from just-now-qa.

Related Issues (18)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.