等待多个延迟对象完成

Ben*_*ter 2 javascript jquery jquery-deferred

等待多个延迟对象完成时,为什么:

$.when(tasks).then(function() {
    document.write("Completed all requests." + "<br/>");
});
Run Code Online (Sandbox Code Playgroud)

立即执行

$.when.apply(null, tasks).then(function () {
    document.write("Completed all requests." + "<br/>");
});
Run Code Online (Sandbox Code Playgroud)

等到任务完成.

Jos*_*ber 11

when函数不采用延迟数组.相反,您将每个延迟传递为单独的参数.这正是apply为你做的.

null被传递到apply仅仅是因为这是apply预计:第一个参数是什么功能的情况下,应设置为它的调用时,第二个参数始终是一个数组,这将扩大,这样的功能将被称为如果数组中的所有项都已作为单独的参数传入.

因为when它的目的与它所调用的上下文没有区别,所以与null其他任何东西一样有效.我更喜欢传递jQuery本身:

$.when.apply($, tasks).then(function () {
    // Whatever
});
Run Code Online (Sandbox Code Playgroud)

因为我认为它看起来更干净,但那只是我.它没有任何区别.


如果您的浏览器支持本机承诺(或者您正在使用polyfill),则可以使用其all方法,它直接采用一系列承诺:

Promise.all(tasks).then(function (values) {
    // "values" is an array, with the results of each of the "tasks"
});
Run Code Online (Sandbox Code Playgroud)