Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async request into for loop angular.js

I have an array and i need to send values of array to webservice through http post request one by one . For the node.js , i'm using "async" package to do that for ex: async.eachSeries doing it well , how can i do that same thing for angular.js , my normal async code;

//this code sends all queries of array (maybe  5.000 request at same time , it is hard to process for webservice :=) ) at same time and wait for all responses. 
//it works but actually for me , responses should wait others at end of loop should work one by one 
//like async.eachSeries module!

    for (var i = 0; i < myArr.lenght; i++) {
        (function (i) {
                var data = {
                    "myQuery": myArr[i].query
                };
                $http.post("/myServiceUrl", data).success(function (result) {
                    console.log(result);
                });
        })(i);
}

Both Matt Way and Chris L answers Correct , you can investigate Chris's answer for understanding about async to sync functions in for loops.

like image 499
Erdi Avatar asked Dec 08 '25 22:12

Erdi


2 Answers

You can use $q to create a similar requirement by chaining promises together. For example:

var chain = $q.when();
angular.forEach(myArr, function(item){
    chain = chain.then(function(){
        var data = {
            myQuery: item.query
        };
        return $http.post('/myServiceUrl', data).success(function(result){
            console.log(result);
        });
    });
});

// the final chain object will resolve once all the posts have completed.
chain.then(function(){
    console.log('all done!');
});

Essentially you are just running the next promise once the previous one has completed. Emphasis here on the fact that each request will wait until the previous one has completed, as per your question.

like image 159
Matt Way Avatar answered Dec 10 '25 10:12

Matt Way


function logResultFromWebService(value)
{
    $http.post("/myServiceUrl", value).success(console.log);
}

angular.forEach(myArray, logResultFromWebService);
like image 31
B. McCartney Avatar answered Dec 10 '25 10:12

B. McCartney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!