提高jQuery的deferred.then()一旦所有递延对象已得到解决 [英] raising jquery deferred.then() once all deferred objects have been resolved

查看:124
本文介绍了提高jQuery的deferred.then()一旦所有递延对象已得到解决的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个JavaScript函数,保存()白水回收(),设置如下:

 函数保存(数据){
    返回.post的$('/保存,数据);
}

功能白水回收(回调){
    VAR dataArray中= [];
    $每个(dataArray中,函数(){
        保存(本);
    });
    回电话();
}
 

我感兴趣的是修改白水回收(),这样它利用jQuery的延迟对象,并引发回调功能一旦所有保存()操作完成。但是,我不能确定确切的语法...特别是与关系到$每个()的$。当()内。会是这样呢?

 函数白水回收(回调){
    VAR dataArray中= [];
    $。当(
        $每个(dataArray中,函数(){
            返回保存(本);
        })
    )。然后(回调);
}
 

解决方案

作为礼指出,$。当()接受一个逗号分隔的参数列表,而不是一个数组。使用 Function.apply()通过数组中,似乎这样的伎俩。

 函数白水回收(回调){
    VAR dataArray中= [],deferreds = [];
    $每个(dataArray中,函数(){
        deferreds.push(保存());
    });

    $ .when.apply(窗口,deferreds)。然后(回调);
}
 

i have two javascript functions, save() and saveAll(), set up as below:

function save(data) {
    return $.post('/save', data);
}

function saveAll(callback) {
    var dataArray = [];
    $.each(dataArray, function() {
        save(this);
    });
    callback();
}

i'm interested in modifying saveAll() so that it leverages jquery deferred objects, and raises the callback function once all save() operations have completed. however, i'm unsure of the exact syntax... specifically with relation to the $.each() inside of the $.when(). would it be something like this?

function saveAll(callback) {
    var dataArray = [];
    $.when(
        $.each(dataArray, function() {
            return save(this);
        })
    ).then(callback);
}

解决方案

as Eli pointed out, $.when() accepts a comma separated list of arguments and not an array. using Function.apply() to pass in the array seems to do the trick.

function saveAll(callback) {
    var dataArray = [], deferreds = [];
    $.each(dataArray, function() {
        deferreds.push( save() );
    });

    $.when.apply(window, deferreds).then(callback);
}

这篇关于提高jQuery的deferred.then()一旦所有递延对象已得到解决的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆