Reputation: 1277
I have an array with filenames and i need to retrieve all those files with ajax requests and wait for them to finish to initialize my stencil.
$.when(req[0],req[1],req[2],req[3],req[4],req[5],req[6],req[7]).done(function(){
for (var i in arr)
Stencil.push(new Platform(importedData[i].cells[0]));
$(".se-pre-con").fadeOut("slow");;
})
AS you can see i fixed the number of the request to wait for, and it's no good. How can i wait for all thoses requests dynamically, the number of the requests is the length of my array.
Upvotes: 4
Views: 1404
Reputation: 93631
You can apply when
to an array like this:
$.when.apply($, req).done(function(){
for (var i in arr)
Stencil.push(new Platform(importedData[i].cells[0]));
$(".se-pre-con").fadeOut("slow");
});
The array has to be filled with jQuery promises, so best to use the result of a function that processes one file and returns a promise and store those in the array.
If you can provide more information about what you do with the files, I will update the example to match.
Here is a little sample that simulates asyc file processing (using a timer):
JSFiddle: http://jsfiddle.net/TrueBlueAussie/79bp8yw1/
var files = ["file1", "file2", "file3", "file4"];
var req = [];
for (var i = 0; i < files.length; i++){
req.push(processFile(files[i]));
}
$.when.apply($, req).done(function(){
$('#body').append("All done");
});
and the dummy file processing function returns a promise:
var time = 1000;
function processFile(filename){
var def = $.Deferred();
setTimeout( function(){
$('body').append("File " + filename + "<br/>");
def.resolve();
}, time);
time += 1000;
return def.promise();
}
Upvotes: 3
Reputation: 337723
You can fill an array with all the promises returned from those AJAX calls, then apply that to the $.when
. Try this:
$.when.apply($, req).done(function() {
// your logic here...
});
Upvotes: 0