I need to do some async ajax calls and in the end of every single one I push a number to an array when all ajax calls finished I call my callback function with this array. But can't figure out how to do so..
So I've tried to implement the deferred method in my code like shown here
Ended up like this:
function uploader(uploads, cb) {
var def = [];
var reslist = [];
$.each(uploads,function(key,value){
if(!value.sync){
def.push(_upload(value));
}
});
function _upload(upload){
var dfd = $.Deferred();
getAntrag(upload.timestamp, function(json) {
$.ajax({
url: 'http://api.***.com/',
type: "POST",
data: {
customer: json
},
async: false,
success: function(msg) {
try {
var res = JSON.parse(msg);
} catch (err) {
dfd.reject();
}
if (res.mldgcode === '0000') {
reslist.push(res.data.ident);
dfd.resolve();
} else {
dfd.reject();
}
}
});
});
return dfd.promise();
}
$.when.apply($,def).done(function(){
console.log('all done');
cb(reslist);
});
$.when.apply($,def).fail(function(args){
console.log('failargs',args);
cb(args);
});
}
So but now the done handler is called before my dfd.resolve()
.
What do I miss here ?