gpt4 book ai didi

javascript - 理解 Promise.all

转载 作者:行者123 更新时间:2023-12-03 07:57:25 25 4
gpt4 key购买 nike

考虑以下我从 https://stackoverflow.com/a/28250704/460084 获取的代码

function getExample() {
var a = promiseA(…);
var b = a.then(function(resultA) {
// some processing
return promiseB(…);
});
return Promise.all([a, b]).spread(function(resultA, resultB) {
// more processing
return // something using both resultA and resultB
});
}

以及我创建的代码演示 https://jsfiddle.net/Lsobypup/

这个想法是运行多个 Promise 并根据其结果返回一些复合值。

我不明白的是为什么在上面的代码中promiseA只运行一次?在我看来,使用 Promise.all([a, b]) 它应该首先在评估 a 时运行,然后在评估 b 时再次运行,因为它依赖于 a。但正如演示所示,这并没有发生。

Promise.all 中有什么魔法可以实现这一点吗?这种行为有哪些规则?

最佳答案

var b = a.then(function(resultA) {
// some processing
return promiseB(…);
});

这是链接 a 的结果,这意味着如果 a 处于已完成状态,将立即调用回调。您对 Promise a 的解析首先发生,因为它是在 all() 调用中首先遇到的。一旦实现,最终值(value)将始终遵循 promise 。

据此MDN reference :

Internally, a promise can be in one of three states:

  • Pending, when the final value is not available yet. This is the only state that may transition to one of the other two states.
  • Fulfilled, when and if the final value becomes available. A fulfillment value becomes permanently associated with the promise. This may be any value, including undefined.
  • Rejected, if an error prevented the final value from being determined. A rejection reason becomes permanently associated with the promise. This may be any value, including undefined, though it is generally an Error object, like in exception handling.

关于javascript - 理解 Promise.all,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34743095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com