Patrick Muñoz Vargas Patrick Muñoz Vargas - 3 months ago 7
AngularJS Question

Post promise returns ids that are needed for another post promise

I am using http post methods to get the data from an endpoint to populate a table. I first need to get the id of the recipients, and subsequently I need to use the Id of these recipients to grab an object belonging to the recipient from another endpoint.

I have a http post that returns a promise. Using .then, I store these id numbers which I store on a javascript array. I then need to make one http post for each id on the array that will return another promise. Not sure if this is the best way to go:

getRecipients = httpService.doPost("/search", [], {userId:"test"});
getRecipients.then(function(recipientData){
vm.recipients = recipientData.data.recipients;
}).then(function(){
for(x in vm.recipients)
{
httpService.doPost("/searchObjects", [], vm.recipients[x].id)
.then(function(){
//store each object returned on another array here....
});
}
});


NOTE: doPost(endpoint, not used, parameters to do the search)
With the above method, the problem is that the for loop will not wait for the then and will move to the next iteration once the doPost has been called.

I guess I can use bluebird, but not sure if that would be the best way to go in here, and if so, how should it be done (note that this is server side javascript so require is not available per say unless I use require.js)?

Answer

If I'm understanding you correctly, you're looking for something like this:

getRecipients = httpService.doPost("/search", [], {userId:"test"});
    getRecipients.then(function(recipientData){
        vm.recipients = recipientData.data.recipients; 
        var promises = [];
        for (x in vm.recipients) {
           promises.push(httpService.doPost("/searchObjects", [], vm.recipients[x].id));
        }

        // in this case $q.all waits for all of the requests to finish 
        // then gives the responses
        $q.all(promises).then(function(responses) {
            // responses is an array of the responses 
            // from each request in the promise array
        });    
    });
Comments