简体   繁体   中英

How do I access the service response data if I am returning an array of custom map with promise as an object?

Here is my code:

function myobject(name, anotherArray){
 this.name = name; this.anotherArray = anotherArray;
}

//$scope.myObjects is an array of myObject


function pMap(name, promise){
    this.name= name;
    this.promise = promise;
};

var getAllPromises = function(){
    var promises = [];
    angular.forEach($scope.myobjects, function(myobject) {
        urlPath = <someurl>+myobject.name;
        var promise = $http({
            url   : urlPath,
            method: 'GET'
        });
        promises.push(new pMap(myobject.name, promise));
    });
    return $q.all(promises);
};

Now when I accept each promise as follows in a separate function using .then, I am not sure how to access the json returned by the service above?

 getAllPromises.then(function(pData){
                    angular.forEach(pData, function(pMap){
                        var name = pMap.name;
                        var responseArray = promiseMap.<?> --> how do I access the json returned by the service here?
<I need to assign $scope.myobjects.anotherArray to data returned by the promise but this has to be done using the name attribute of each myobject>

                    });
                });

Any ideas how to do this? New to promise pattern and angularjs in general

You could just do this:

var promises;
angular.forEach($scope.myobjects, function(myobject) {
    var promise = $http({
        url   : urlPath,
        method: 'GET'
    });
    promises.push(promise);
});
$q.all(promises).then(function(resolvedPromises) {
  var firstPushedPromise = resolvedPromises[0];
  //var xPushedPromise = resolvedPromises[x];
}

resolvedPromises is an array here, the index will be the same as you pushed them in. You can just access every other promise by their index.

I'm not sure why you're looping over $scope.myobjects if you're not going to use myobject though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM