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?
Use
$.map
instead of$.each
: