javascript - 如何确保 $.each 推送 jQuery 中的所有延迟?

标签 javascript jquery deferred

我有以下 jQuery 代码:

    myFunc: function(cmd, obj){ 
        var idToExtMap = this. map;
        var requireRes = this.reqInst;
        var deferreds = [];
        var ret = true;
        $.each(idToExtMap[cmd], function(key, ext){
                if(ext.$classIns && ext.$classIns.prepare) {
                    var returnedValue = ext.$classIns.prepare(obj);
                    deferreds.push(returnedValue);
                    $.when(returnedValue).done(function(satisfied){
                        if(ret!==false){
                            ret = satisfied;
                        }
                    });
                } else {
                    requireRes(ext).done(function(){
                        var cls = $.toFunction(ext.$jscls);
                        if(cls) {
                            ext.$classIns = new cls();
                            if(ext.$classIns.prepare){
                                var returnedValue = ext.$classIns.prepare(obj);
                                deferreds.push(returnedValue);
                                $.when(returnedValue).done(function(satisfied){
                                    if(ret!==false){
                                        ret = satisfied;
                                    }
                                });
                            }
                        }
                    });     
                }   
            });

            $.when.apply(null, deferreds).done(function(){
                return ret;
            });
        }

我遇到的问题是 $.when.apply 在所有 deferreds 被插入 deferreds 数组之前执行。如何确保 $.when.apply 仅在所有 deferreds 被插入 deferreds 数组后才执行?

最佳答案

您要做的主要事情是确保 promise 同步推送到数组中。通过将 deferreds.push(...) 隐藏在完成回调中,push() 是异步的,并且当 $ 时数组仍保证为空。 when.apply(...) 被执行。

其他一些问题也可以解决:

  • 可以通过重新排列来避免 ext.$classIns.prepare(obj) 周围的代码重复。
  • 可以通过利用 Promise 拒绝来避免麻烦的外部变量 ret

经过一些其他的小整理,我最终得到了这个(未经测试):

myFunc: function(cmd, obj) {
    var requireRes = this.reqInst;
    var promises = $.map(this.map[cmd], function(key, ext) {
        var p; // p for promise
        if(ext.$classIns) {
            p = $.when(ext.$classIns);
        } else {
            p = requireRes(ext).then(function() {
                var cls = $.toFunction(ext.$jscls);
                if(cls) {
                    ext.$classIns = new cls();
                }
                return ext.$classIns || null;
            });
        }

        /* At this point, `p` is a promise resolved with either a previously created `cls()` object or a freshly created one */

        // As we are inside `$.map(...)`, `return p.then(...)` causes the promise delivered by `p.then(...)` to be pushed onto the `promises` array.
        return p.then(function($classIns) {
            if($classIns && $classIns.prepare) {
                return $classIns.prepare(obj).then(function(satisfied) {
                    if(!satisfied) {
                        // Here, returning a rejected promise is equivalent to setting the original `ret` irrevocably to `false`.
                        return $.Deferred().reject(new Error(".prepare() not satisfied"));
                    }
                });
            } else {
                // You may want also to reject if `$classIns` or `$classIns.prepare` doesn't exist.
                // If not, then delete this else{} clause.
                return $.Deferred().reject(new Error(".prepare() could not be called"));
            }
        });
    });

    /* At this point, `promises` is an array of promises - some or all resolved, some or all pending */

    // Here, instead of the boolean `ret`, you can exploit the joined promise's success/error paths :
    // * success path is equivalent to ret == true.
    // * error path is equivalent to ret == false, or any unpredicted error.
    return $.when.apply(null, promises).then(function() {
        // Success.
        // Do whatever is necessary here or in `myFunc().then(function() {...})`.
    }, function(e) {
        // An error occurred.
        // Do whatever is necessary here or in `myFunc().then(null, function() {...})`.
        console.error(e); //for example
    });
}

评论应该解释正在发生的事情。

关于javascript - 如何确保 $.each 推送 jQuery 中的所有延迟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29860387/

相关文章:

javascript - 延迟函数解析

javascript - iframe 阻止 javascript 工作

javascript - 当条件和字段名称相同时,如何不允许项目数组中出现重复项?

javascript - 延迟加载 jquery 后替换 $(document).ready(function()

没有对话框的 jQuery UI 覆盖

jquery - 如何选择一系列列表项元素,将它们分成两组并将每个组包装在新的周围 DIV 中

node.js - 具有延迟约束的 Postgres Sequelize 事务不起作用

javascript - html5文件api,将用户选择的目录存储在sessionStorage中?

javascript - Zendesk 应用程序错误和 Webhook 发布延迟/失败

javascript - Angular 表单提交不检查表单验证