​jquery deferred in .each loop​

​Ask Question​​​ Asked 7 years, 3 months ago Active ​​7 years, 3 months ago​​ Viewed 26k times 27 8

This should be a simple one. I have a function that is called and I need to wait for all the async operations to complete. what I want is something like this...

self.processSchema(data).done(function(results){ //do stuff}); 

The processSchema function loops using $.each and calls an async method.

var processSchema = function(data) {      var def = new $.Deferred();      $.each(table, function()      {          //calls an async SQLitePlugin method          db.executeSql(sql, data, function(tx, results){             def.resolve(results);          }      }       return(def.promise()); } 

This does not seem to work, I am new to $.Deferred so any guidance would be helpful

​javascript​​​​jquery​​​​loops​​​​deferred​​​ ​​Share​​​ Edit Follow asked Dec 19 '13 at 18:14 ​​​gdex​​ 45511 gold badge44 silver badges99 bronze badges


  • I think you would need a new deferred for every single db.executeSql, and then do a large $.when(deferred1, deferred2...defferedN).then(function(data1, data2...dataN) { }); – ​​Robin Giltner​​​ ​​Dec 19 '13 at 18:17​

​Add a comment​

2 Answers

​Active​​​​Oldest​​​​Votes​​ 36

You'll need a promise for each iteration

var processSchema = function(data) {      var promises = [];       $.each(table, function() {          var def = new $.Deferred();          db.executeSql(sql, data, function(tx, results){             def.resolve(results);          });          promises.push(def);      });       return $.when.apply(undefined, promises).promise(); } 

​Share​​​ Edit Follow ​​edited Dec 19 '13 at 18:38​​​ answered Dec 19 '13 at 18:19 ​​​adeneo​​ 291k2626 gold badges358358 silver badges360360 bronze badges

​Show 6 more comments​​ 8

For Functional Programming fiends (like myself), here's a single-expression version of ​​adeneo's answer​​:

var processSchema = function(data) {     return $.when.apply($, $.map(table, function() {         var def = new $.Deferred();         db.executeSql(sql, data, function(tx, results){             def.resolve(results);         });         return def;     })).promise(); }; 

Also I'd like to note that you are iterating over ​​table​​​, but aren't doing anything with each item in the iteration (i.e. the callback in your ​​each​​ has no arguments.) Now, I'm not sure what your goal is, but this doesn't seem right to me :P


What Doesn't Kill Me Makes Me Stronger