jQuery Multiple getJSON requests

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);

Answer

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.