Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Deferred - waiting for multiple AJAX requests to finish [duplicate]

I have a three layer deep chain of deferred ajax calls, and ideally they are going to kick the promise all the way up when the deepest layer finishes (makes me thing of Inception... "we need to go deeper!").

The problem is that I'm sending off many ajax requests (possibly hundreds) at once and need to defer until all of them are done. I can't rely on the last one being done last.

function updateAllNotes() {     return $.Deferred(function(dfd_uan) {         getcount = 0;         getreturn = 0;         for (i = 0; i <= index.data.length - 1; i++) {             getcount++;             $.when(getNote(index.data[i].key)).done(function() {                 // getNote is another deferred                 getreturn++             });         };         // need help here         // when getreturn == getcount, dfd_uan.resolve()     }).promise(); }; 
like image 556
brittohalloran Avatar asked Jun 30 '11 17:06

brittohalloran


1 Answers

You can use .when(), and .apply() with multiple deferred. Extremely useful:

function updateAllNotes() {     var getarray = [],         i, len;      for (i = 0, len = data.length; i < len; i += 1) {         getarray.push(getNote(data[i].key));     };      $.when.apply($, getarray).done(function() {         // do things that need to wait until ALL gets are done     }); } 
like image 199
brittohalloran Avatar answered Sep 21 '22 08:09

brittohalloran