我一直在通过 this link 研究 Promise我明白了它的想法
var parentID;
$http.get('/api/user/name')
.then(function(response) {
parentID = response.data['ID'];
for (var i = 0; i < response.data['event-types'].length; i++) {
return $http.get('/api/security/' + response.data['event-types'][i]['key']);
}
})
.then(function(response) {
// response only returns one result of the many promises from the for loop
// do something with parentID;
});
但是,我的用例需要循环并发送创建多个 promise 。我尝试链接上面的示例,但只有从 for 循环创建的唯一一个 promise 被执行。
如何在继续访问变量parentID的同时继续链接所有 promise ?
最佳答案
您应该使用$q.all
,因为它与 AngularJS 摘要周期集成。
var parentID;
$http.get('/api/user/name')
.then(function(response) {
parentID = response.data['ID'];
var promiseList = [];
for (var i = 0; i < response.data['event-types'].length; i++) {
var iPromise = $http.get('/api/security/' + response.data['event-types'][i]['key']);
promiseList.push(iPromise);
};
return $q.all(promiseList);
})
.then(function(responseList) {
console.log(responseList);
});
来自文档:
all(promises);
Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.
Parameters
An array or hash of promises.
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.
关于javascript - 链接通过 for 循环创建的多个 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38555228/