w292614191
V2EX  ›  问与答

Promise.all 嵌套 Promise.all 顺序错乱?

  •  
  •   w292614191 · Dec 6, 2022 · 2498 views
    This topic created in 1434 days ago, the information mentioned may be changed or developed.
    我有下面这段代码,理论应该先输出“11111111”在输出“cccc”。

    https://imgur.com/a/YuHi7NC.png

    实际在控制台却不是这样的。

    https://imgur.com/u98fTNa.png


    哪位大佬能分享下这是为什么吗?
    17 replies  •  2022-12-07 11:05:46 +08:00
    w292614191
    w292614191
    OP
    Dec 6, 2022
    1




    补两张图。
    timethinker
    timethinker
    Dec 6, 2022❤️1
    2
    Promise 构造函数传入的 executor 函数会被立即执行。
    pixcai
    pixcai
    Dec 6, 2022
    3
    2 楼说的对
    churchill
    churchill
    Dec 6, 2022
    4
    johnli
    johnli
    Dec 6, 2022
    5
    2 楼说的对,所以依赖的顺序是 resolve 的结果,不是中间过程
    w292614191
    w292614191
    OP
    Dec 6, 2022
    6
    @timethinker #2 也就是在需要的时候构建,而不是提交构建放哪里?
    w292614191
    w292614191
    OP
    Dec 6, 2022
    7
    @timethinker #2 而不是提前构建好。
    w292614191
    w292614191
    OP
    Dec 6, 2022
    8
    @timethinker #2 还是不对,我不调用 Promise.all ,他们也执行,这是啥逻辑?

    应该是 Promise.all 然后才会并发执行吧?
    w292614191
    w292614191
    OP
    Dec 6, 2022
    9
    如果是“立即执行” ,Promise.all 的意义是啥?结果都产生了。
    timethinker
    timethinker
    Dec 6, 2022
    10
    Promise != Lazy ,你需要的更像是 Lazy
    timethinker
    timethinker
    Dec 6, 2022❤️1
    11
    w292614191
    w292614191
    OP
    Dec 6, 2022
    12
    @timethinker #11 学习了,非常感谢,我现在理解了。
    jadehare
    jadehare
    Dec 6, 2022
    13
    @w292614191 #9
    let getSys = function(resolve){
    console.log("111")
    resolve();
    }
    ruleArr.push(getSys);

    Promise.all(ruleArr.map(a=>new Promise(a)));
    Yeen
    Yeen
    Dec 6, 2022
    14
    你传给 promise 的异步回调本身并不能保证同步顺序。
    这个问题简化一下更好理解。你构造两个 promise ,都是 http 请求。你并不能保证哪个请求先返回。
    如果需要同步,要么在 then 串行起来;要么 await 同步。
    Yeen
    Yeen
    Dec 6, 2022
    15
    @w292614191 立即执行不等于立即有结果。比如网络请求
    okakuyang
    okakuyang
    Dec 7, 2022
    16
    可以在 for of 里用 awit 顺序执行
    ZoeeoZ
    ZoeeoZ
    Dec 7, 2022
    17
    promise.all 我遇到过最迷幻的一次问题是: 里边的两个(校验表单的)函数调换一下顺序(比如 B,A)就永远走失败,但不调换(A,B)就正常,我调了 N 久才发现是这俩顺序的问题
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   983 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 19:19 · PVG 03:19 · LAX 11:19 · JFK 14:19
    ♥ Do have faith in what you're doing.