简体   繁体   English

jquery在.each循环中延迟

[英]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(data).done(function(results){ //do stuff});

The processSchema function loops using $.each and calls an async method. processSchema函数使用$ .each循环并调用异步方法。

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 这似乎不起作用,我是$的新手。推迟所以任何指导都会有所帮助

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

For Functional Programming fiends (like myself), here's a single-expression version of adeneo's answer : 对于功能编程恶魔(像我一样),这里是adeneo答案的单表达式版本:

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 (ie 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 此外,我想指出,你遍历table ,但不这样做,在迭代每个项目的任何东西(即你的回调each没有参数)。现在,我不知道你的目标是什么,但这对我来说似乎不对:P

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM