Getting multiple ajax with jQuery.each, when (jQuery.when) all done do something

3.5k views Asked by At

I wish to have a function which accepts an array of urls as argument, then downloads the json for each of those urls asynchronously, and when all are completed do some function.

First I have a function that returns the ajax to get one url (deferred/promise object).

function get_json(url) {
    /* Asynchronously download data of type json */
    return $.ajax({url: url,
                   dataType: 'json'});
}

Doing the following works:

var url = 'http://data.hisparc.nl/api/station/501/';
get_json(url).done(function(data){console.log(data)});

So, now I want to be able to give an array of urls and then be able to attach a done to do something when done. I came up with this:

function get_multiple_json(urls) {
    /* Asynchronously download multiple urls of type json */
    return $.when($.each(urls, function(i, url) {return get_json(url);}));
}

So I would assume this works:

var urls = ['http://data.hisparc.nl/api/station/501/',
            'http://data.hisparc.nl/api/station/505/'];
get_multiple_json(urls).done(function() {alert('hi')});

But the alert is thrown before the ajax are finished, it seems that $.each does not return the deferred objects.

So how should I do this?

2

There are 2 answers

0
Alon Gubkin On BEST ANSWER

Use $.map instead of $.each:

var urls = ['http://data.hisparc.nl/api/station/501/',
            'http://data.hisparc.nl/api/station/505/'];

$.when.apply(null, urls.map(function (url) {
    return $.ajax({ url: url, dataType: 'json' });
})).then(function () {
   alert("hi");
});
0
AudioBubble On
(function($) {
    var arrTest = ['http://data.hisparc.nl/api/station/501/',
               'http://data.hisparc.nl/api/station/505/'];
    $(arrTest).each(function(intIndex, strElem) {
        var objJson = $.getJSON(strElem);
        $(objJson).each(function(intIndex, strElem) {
           // do parsing here
        });
    });
})(jQuery);

This should help.