在AngularJS中链接未知数量的承诺

前端之家收集整理的这篇文章主要介绍了在AngularJS中链接未知数量的承诺前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
好吧,假设我有一系列n个XHR请求:
var promises = [];
var AllResults = [];
$scope.requests = [
    {
        "uri":"http://foo/bar/action1","name":"Action1"
    },{
        "uri":"http://bar/foo/action2","name":"Action2"
    },{...},{...}
];
var ParseMyResultsArray = function(){
    console.log(AllResults);
    //...
};

angular.forEach($scope.requests,function(request){
    var promise = $http.get(request.uri);
    promises.push(promise);
});

angular.forEach(promises,function(promise){
    promise.then(function(results){
        AllResults.push(results);
    });
});

//Then,when all promise are resolved...
ParseMyResultsArray();

如果在不知道请求数组的大小的情况下解析了所有的promises,我怎么能确定调用ParseMyResultsArray()?

谢谢你的帮助!

从angular docs到 $http

The $http API is based on the deferred/promise APIs exposed by the $q
service.

因此,可以使用$q.all()方法获取一系列承诺,并且:

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

实现代码是:

$q.all(promises).then(function () { /* All promises are resolved */ });
原文链接:https://www.f2er.com/angularjs/142389.html

猜你在找的Angularjs相关文章