gpt4 book ai didi

angularjs - 等待所有 promise 解决和/或拒绝?

转载 作者:行者123 更新时间:2023-12-02 23:16:13 25 4
gpt4 key购买 nike

我需要并行发出的多个请求的拒绝/分辨率值数组。 Angular $q 不提供这样的选项($q.all 仅当每个请求都得到解决时才会返回值数组!)。

是否有 Angular 的方法可以做到这一点,或者我应该寻找一些第三方 promise 处理库,比如原始的 Q?

最佳答案

据我所知,Angular $q 服务不提供此功能。然而,它可以在 Kris Kowal 的(原始)Q 中作为 allSettled 使用。

示例来自 the docs :

Q.allSettled(promises)
.then(function (results) {
results.forEach(function (result) {
if (result.state === "fulfilled") {
var value = result.value;
} else {
var reason = result.reason;
}
});
});

您可以查看the source code对于此方法并在 Angular 中自行实现

/**
* Turns an array of promises into a promise for an array of their states (as
* returned by `inspect`) when they have all settled.
* @param {Array[Any*]} values an array (or promise for an array) of values (or
* promises for values)
* @returns {Array[State]} an array of states for the respective values.
*/
Promise.prototype.allSettled = function () {
return this.then(function (promises) {
return all(array_map(promises, function (promise) {
promise = Q(promise);
function regardless() {
return promise.inspect();
}
return promise.then(regardless, regardless);
}));
});
};

但我的建议是使用标准 Q 库并将其包装在 Angular 服务中。

关于angularjs - 等待所有 promise 解决和/或拒绝?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33952852/

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