6

My script needs to fetch several json files on https://graph.facebook.com/xxxx, and retrieve a certain field from each json, then calculate summation.

My problem is how to print out the result after all getJSON done? With below code it will prints 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);
2
  • Would you mind to post an example json object? Even though Facebook is the biggest social network side, not all users -like me- are registered at facebook. Thx Commented Apr 28, 2011 at 11:30
  • example object is irrelevant :) see answer below Commented Apr 28, 2011 at 11:30

2 Answers 2

23

Using jQuery 1.5 deferred objects:

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

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

and only $.when they're all .done():

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

NB: this will accumulate result in the order that the AJAX calls complete, not in the order they're made.

Sign up to request clarification or add additional context in comments.

1 Comment

@Alnitak how can i handle, if the getJson failed, because the url dont exist?
3

It's not working as you are printing the result straight away, remember that the code where you concatenate the result is a callback so will fire after your alert.

On each callback you'll have to check if all have finished. replace the alert() call with your 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);
            }
        })
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.