Polly
Polly

Reputation: 599

Constructing jquery's deferred object when parameters programatically

I'm new to javascript and jquery, and I'm learning how to use jquery's Deferred object to wait for a loop to complete before performing an action. The functions inside the loop don't need to be called in any special order. In other words, function n isn't dependent on the outcome of function n-1, so I'm not chaining them together with a pipe.

So far I have this, which works:

// wait some random amount of time, then log a message
// and resolve the Deferred object
function doTask(id) {
  var defer = $.Deferred();
  setTimeout(function() {
    console.log(id + " finished!");
    defer.resolve(id);
  }, Math.random()*1000);
  return defer.promise();
}

// log when these three independent tasks complete
$.when( doTask("foo1"), doTask("foo2"), doTask("foo3")).done(function() {
    console.log(" ... all done in no particular order!");
});

But I'd like to construct the parameter list for $.when programmatically. How do I do that?

Upvotes: 0

Views: 161

Answers (1)

Kevin B
Kevin B

Reputation: 95054

Create an array and apply it to $.when.

var defArr = [];

defArr.push(doTask("foo1"));
defArr.push(doTask("foo2"));
defArr.push(doTask("foo3"));

$.when.apply(null,defArr).done(function(){
    console.log(" ... all done in no particular order!");
});

Upvotes: 2

Related Questions