javascript - jQuery deferred array not triggering .done() as expected -


i'm having trouble jquery deferreds. here's code:

function makeajaxcalls(purge){   var deferreds = [];   // delete documents   _.each(purge, function(element, index, list){     console.log('purging '+element.model+' id='+element.id);     deferreds.push(       $.ajax({         type: 'delete',         url: '/api/admin/purge/'+element.model+'/'+element.id       })     );   });   console.log('returning array '+deferreds.length+' deferreds');   return deferreds; };  function purgedeleteddocs(){   console.log('purging...');   var purge = [];   _.each(arrayofids, function(element, index, list){     purge.push({'model': arrayofmodels.get(element).get('modelname'), 'id': element});   }); // [{model: 'modelname', id: 'id'}...]   // when *all* ajax calls resolved run code   $.when.apply(this, deferreds).done(function(){     console.log('done');   });   var deferreds = makeajaxcalls(purge); };  purgedeleteddocs() 

as can see i'm using $.when.apply i'm returning array of deferreds makeajaxcalls() function.

here's i'm getting in console:

purging... done purging user id=5564e0f647f054512a9d64c9 purging client id=557079a04407058a49fd2f3d returning array 2 deferreds 

now that's odd. i'm seeing done before ajax calls have been made, let alone resolved. i'm passing this apply() using $ etc. makes no difference - , reading docs apply() first parameter sets this code that's expected behaviour.

the server correctly getting api calls made ajax calls being made, it's multiple deferreds seem resolve , trigger .done() before they're made.

any ideas doing wrong?

// when *all* ajax calls resolved run code $.when.apply(this, deferreds).done(function(){     console.log('done'); }); var deferreds = makeajaxcalls(purge); 

as can see i'm using $.when.apply i'm returning array of deferreds makeajaxcalls() function.

well you're not passing them $.when function. instead, passing undefined $.when, before making call makeajaxcalls()!

reorder statements to

var deferreds = makeajaxcalls(purge); $.when.apply(this, deferreds).done(function(){     console.log('done'); }); 

Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -