jquery deferred in .each loop

gdex picture gdex · Dec 19, 2013 · Viewed 26k times · Source

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

Answer

adeneo picture adeneo · Dec 19, 2013

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();
}