最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Waiting for multiple deferred objects to complete - Stack Overflow

programmeradmin3浏览0评论

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

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

execute immediately, yet

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

waits until the tasks have pleted.

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

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

execute immediately, yet

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

waits until the tasks have pleted.

Share Improve this question edited Jan 29, 2013 at 1:52 Joseph Silber 220k59 gold badges368 silver badges292 bronze badges asked Jan 29, 2013 at 1:46 Ben FosterBen Foster 34.8k41 gold badges180 silver badges290 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

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.

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.

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.


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"
});
发布评论

评论列表(0)

  1. 暂无评论