I am retrieving a series of data from a server (geoserver) using $.ajax.
The (simplified) request looks like this:
var dataList=[];
//var urllist= // a list of several URLs to request data from
$.each(urllist,function(i) {
$.ajax({
jsonpCallback: 'getJson',
type: 'GET',
url: urllist[i],
dataType: 'jsonp',
success: function(data) {
dataList[i]=data.value;
}
})
});
I need to write to the global variable dataList
because I need to fire an event after all requests from urllist are finished. (I've got deferreds implemented like so).
The problem is that the finished list is always in a different order. I need the result to be in the same order as the requests.
It might be a problem of closure where the index i
that is passed on to the ajax function and the allocation to dataList
that is happening at a later point (when the each loop has moved on). I tried taking care of that like this but the problem remains the same. Also $.each
like in the code above should create a seperate closure for every iteration anyway.
I've managed to implement a recursive function but its synchronous.
edit: suggested duplicate does not deal with looped ajax requests
You can access all the results in $.when
callback in the correct order
// map an array of promises
var deferreds = urllist.map(function(url){
// return the promise that `$.ajax` returns
return $.ajax({
url: url,
dataType: 'jsonp'
}).then(function(data){
return data.value;
})
});
$.when.apply($, deferreds).then(function(results){
// results will be array of each `data.value` in proper order
var datalist = results;
// now do whatever you were doing with original datalist
$.each(datalist....
}).fail(function(){
// Probably want to catch failure
}).always(function(){
// Or use always if you want to do the same thing
// whether the call succeeds or fails
});
The problem was not related to the deferreds but to the jsonp or the related jsonpcallback
required for the request. Requesting the data as json solved the problem
credits to @charlietfl for the answer over at: Looped ajax request. Error handling and return order
For anyone looking this up: You most likely have to to enable Cross-Origin Resource Sharing on geoserver to be able to access the JSON directly