JQuery Multiple getJSON Queries

My script should get some json files at https://graph.facebook.com/xxxx and get a specific field from each json, and then calculate the summation.

My problem is how to print the result after getJSON completes? With the code below, it will print 0. Feel free to suggest any better approaches.

var result = 0; $.each(urls, function (i, url) { $.getJSON(url, function (json) { result += json.field1; }) }); alert(result); 
+6
source share
2 answers

Using jQuery 1.5 pending objects:

Accumulate an array of JQXHR objects returned by $.getJSON()

 var jxhr = urls.map(function(url) { return $.getJSON(url, function(json) { result += json.field1; }) }); 

and only $.when they are all .done() :

 $.when.apply($, jxhr).done(function() { alert(result); }); 

NB: this will accumulate result in the order in which the AJAX calls end, and not in the order in which they are made.

+23
source

It does not work, since you print the result immediately, remember that the code in which you combine the result is a callback, so it will fire after your warning.

With each callback, you will need to check if everything is over. replace the alert () call with processing. :)

  var result = 0; var doneCount = 0; $.each(urls, function (i, url) { $.getJSON(url, function (json) { doneCount++; result += json.field1; if (doneCount == urls.length) { alert(result); } }) }); 
+3
source

Source: https://habr.com/ru/post/886870/


All Articles