Skip to content Skip to sidebar Skip to footer

Jquery Deferred In .each Loop

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(

Solution 1:

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

Solution 2:

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


Post a Comment for "Jquery Deferred In .each Loop"