0

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?

1 Answer 1

2

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!");
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.