d0001
d0001

Reputation: 2190

Attach callback to multiple jquery promises

I have multiple deferred objects. I need to attach handlers to be fired once per deferred object.

I know that I can use

$.when.apply($, my_array);

but as I understand it, done will only be fired once all deferred objects are resolved.

I need done to be fired every time an object is resolved. I can probably use a loop but I would like to know if there is something like on the lines of the above line using $.when.

Upvotes: 0

Views: 70

Answers (2)

Evan Davis
Evan Davis

Reputation: 36592

You've got to use a loop; there's no syntax sugar for handing each promise individually.

function doneCallback() {
  // your common callback
}

$.each(my_array, function(my_deferred) {
    my_deferred.done(doneCallback);
}

Upvotes: 1

Christopher White
Christopher White

Reputation: 288

Not exactly sure if this is what you're trying to do but it sounds like what you need to do is create a master deferred object then pipe the array of deferred objects to it. Add your handlers to the objects in the array using .always() which fires whether the deferred fails or succeeds. When all of the child deferred objects are resolved the master deferred .done() will fire.

Also $.when() can handle arrays of deferred objects so you could try $.when(my_array).always(function()...)

Upvotes: 0

Related Questions