等待多个延迟的对象完成 [英] Waiting for multiple deferred objects to complete

查看:112
本文介绍了等待多个延迟的对象完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在等待多个延迟的对象完成时,为什么这样做:

When waiting for multiple deferred objects to complete, why does:

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

立即执行

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

等待直到任务完成.

推荐答案

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

The when function does not take an array of deferreds. Rather, you pass each deferred as a separate argument. That's exactly what apply is doing for you.

传递给applynull仅仅是因为apply期望的:第一个参数是函数调用时应设置的上下文,第二个参数始终是数组,将对其进行扩展,以便调用该函数,就好像数组中的所有项目都作为单独的参数传递一样.

The null being passed to apply is just because that's what apply expects: the first argument is what the context of the function should be set to when its called, and the second argument is always an array, which will be expanded so that the function will be called as if all the items in the array have been passed in as separate arguments.

由于出于when的目的,使用什么上下文都没有区别,因此null的工作原理和其他任何事情一样好.我更喜欢将它传递给jQuery本身:

Since for the purpose of when it makes no difference what context it's being called with, null works just as well as anything else. I prefer to pass it jQuery itself:

$.when.apply($, tasks).then(function () {
    // Whatever
});

因为我认为它看起来更干净,但这就是我.没什么区别.

since I think it looks cleaner, but that's just me. It makes no difference whatsoever.

如果您的浏览器支持本机承诺(或者您正在使用 polyfill )您可以改用其all方法,该方法直接接受一个promise数组:

If your browser supports native promises (or you're using a polyfill) you can use its all method instead, which takes an array of promises directly:

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

这篇关于等待多个延迟的对象完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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