Pass in an array of Deferreds to $.when()
发布日期:2021-10-16 14:43:58 浏览次数:5 分类:技术文章

本文共 1408 字,大约阅读时间需要 4 分钟。

339
98

Here's an contrived example of what's going on: 

HTML:

Click me!

JavaScript:

function getSomeDeferredStuff() {
var deferreds = []; var i = 1; for (i = 1; i <= 10; i++) {
var count = i; deferreds.push( $.post('/echo/html/', {
html: "

Task #" + count + " complete.", delay: count }).success(function(data) {

$("div").append(data); })); } return deferreds;}$(function() {
$("a").click(function() {
var deferreds = getSomeDeferredStuff(); $.when(deferreds).done(function() {
$("div").append("

All done!

"); }); });});

I want "All done!" to appear after all of the deferred tasks have completed, but $.when() doesn't appear to know how to handle an array of Deferred objects. "All done!" is happening first because the array is not a Deferred object, so jQuery goes ahead and assumes it's just done.

I know one could pass the objects into the function like $.when(deferred1, deferred2, ..., deferredX) but it's unknown how many Deferred objects there will be at execution in the actual problem I'm trying to solve.

accepted

To pass an array of values to any function that normally expects them to be separate parameters, use Function.prototype.apply, so in this case you need:

$.when.apply($, my_array);

See 

转载地址:https://blog.csdn.net/songchunmin_/article/details/70141198 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:jquery扩展方法
下一篇:食君之禄,忠君之事

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2024年04月17日 00时44分54秒