raising jquery deferred.then() once all deferred o

2019-02-02 18:52发布

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

3条回答
Root(大扎)
2楼-- · 2019-02-02 19:13

The problem I think is that $.each is returning your dataArray, not a list of Deferred objects like you want to feed to $.when.

查看更多
神经病院院长
3楼-- · 2019-02-02 19:25

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);
}
查看更多
可以哭但决不认输i
4楼-- · 2019-02-02 19:26

You should be able to pass a comma-separated list of deferred objects to $.when and .then will execute once they all have resolved.

http://api.jquery.com/jQuery.when/

查看更多
登录 后发表回答