0

Below are my multiple ajax calls in each loop.

var getApiVendorslist = $.getJSON("url");
var sum = 0;

 getApiVendorslist.then(function(res) {
    console.log("Completed Fetching List of vendors");
    $.each(res.data, function(k, v) {
        var ajaxCall = $.getJSON(url);
        ajaxCall.then(function(result) {
            if (result.output=="success") {
                sum += result.balance;
            }
            console.log("Sum : " + sum)
        });
   });
}).then(function(){
    console.log("All Loops Completed");
});
console.log(sum);

When I run above code sequence of consoles are

Completed Fetching List of vendors,
All Loops Completed,
Sum,
Sum,    
Sum....

But I need then to be

Completed Fetching List of vendors,
Sum,
Sum,
Sum....,
All Loops Completed

What modifications should be done in above code to achieve desired result ? I tried using $.each(...).promise().done() but no success. Any Help would be appreciated.

Vibhas
  • 241
  • 5
  • 20
  • Consider using the library Q for control over multiple ajax calls' synchronisation. – victor175 Apr 22 '15 at 14:50
  • 2
    Or push all requests in an array and then use jQuery `when` method, e.g: http://stackoverflow.com/questions/5627284/pass-in-an-array-of-deferreds-to-when – A. Wolff Apr 22 '15 at 14:55
  • @A.Wolff tried that too ... but still same – Vibhas Apr 22 '15 at 15:07
  • @Vibhas So sounds like your code is wrong – A. Wolff Apr 22 '15 at 15:08
  • At last I got to know why @ A.Wolff solution was not working ... problem was say out of 5 if my only 4 ajax call were successful then It has was not resolving all promises. When all Ajax call were successful it printed all done. How can I print all done irrespective of failed[404] ajax calls. ? – Vibhas Apr 23 '15 at 06:46
  • Have moved this question to http://stackoverflow.com/questions/29816137/get-response-of-multiple-deferred-objects-in-jquery – Vibhas Apr 23 '15 at 07:10

0 Answers0