Reputation: 2563
I am trying to make multiple async Ajax calls and want to do some action when all ajax calls are completed. So I am trying to use jquery promise functionality, but it seems like it is calling $.done function before the ajax calls are successful.
Below are my codes:
pool = {a: 1, b: 2};
for(var camp in pool){
promises.push(parseFile(camp));
}
$.when.apply($, promises).done(function() {
console.log("All jobs finished");
});
function parseFile(fname)
{
console.log(fname +" call");
$.ajax({
url: "data/" + fname + ".txt",
dataType: "text"
})
.done(function(data) {
console.log(fname + " done");
});
}
Console Log:
a call
b call
All jobs finished // THIS SHOULD HAVE BEEN CALLED AT THE END
a done
b done
Upvotes: 0
Views: 174
Reputation: 388446
parseFile
need to return a promise other wise the value returned by the method will be undefined, which will be considered as the $.when()
as a resolved value.
function parseFile(fname) {
console.log(fname);
//return the ajax promise here
return $.ajax({
url: "data/" + fname + ".txt",
dataType: "text"
})
.done(function (data) {
console.log(fname + " done");
});
}
Upvotes: 2