gpt4 book ai didi

javascript - 我如何在 angularjs 中使用 $q.all(promises)

转载 作者:行者123 更新时间:2023-11-30 19:13:46 25 4
gpt4 key购买 nike

通常我会做

$http({
method:'GET',
url: 'exmapleURL',
params: {someParams}
}).then(function(response) {
console.log(response); // response contains data I need
});

现在我有多个这样的调用要运行,我想等待它们全部完成,然后再对它们的响应进行处理,而 $q.all() 似乎是一个不错的起点。

根据 AngularJS $q Service API Reference - $q.all文档,

all(promises)

Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.

Returns: Returns a single promise that will be resolved with an array/hash of values, each value corresponding to the promise at the same index/key in the promises array/hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value.

这是否意味着如果我传入一组请求(如 $q.all(calls).then(response)),则返回的 promise 在数组中的顺序为 相同电话是通过的?我可以做类似 response[0] 的事情来检索第 0 次调用返回的响应数据吗?谢谢。

最佳答案

Does this mean that if I pass in an array of requests(like $q.all(calls).then(response)), the returned promises are in an array in the same order as the calls are passed in? Can I do something like response[0] to retrieve the response data returned by the 0th call?

是的,数组中的结果以相同的顺序返回:

angular.module("app",[])
.run(function($q) {
var promise99 = $q.when(99);
var promise22 = $q.when(22);

$q.all([promise22,promise99]).then(function([result22,result99]) {
console.log(result22);
console.log(result99);
});
});
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app"></body>

$q.all 也接受哈希值

angular.module("app",[])
.run(function($q) {
var promise99 = $q.when(99);
var promise22 = $q.when(22);

var promiseHash = {
r99: promise99,
r22: promise22
};

$q.all(promiseHash).then(function(resultHash) {
console.log(resultHash.r22);
console.log(resultHash.r99);
});
});
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app"></body>

有关详细信息,请参阅

关于javascript - 我如何在 angularjs 中使用 $q.all(promises),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58209960/

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