I want to perform a number of actions, which will execute asynchronously (sending data to the server with a 'finished' callback). I then want to trigger an event when all of these tasks complete. Something like a thread join without the threads. I wrote the following helper function, which doe开发者_如何学JAVAs what I want:
// A quick fake for thread joining.
// Allow objects to add and remove themselves. Once they are all removed, call the callback with the context.
function Waiter(callback, context)
{
this.tarriers = [];
this.callback = callback;
this.context = context;
this.add = function(tarrier)
{
this.tarriers.push(tarrier);
}
this.remove = function(tarrier)
{
this.tarriers = _.without(this.tarriers, tarrier);
if (this.tarriers.length == 0)
{
this.callback(this.context);
}
}
return this;
}
But I feel a bit bad about wheel-reinventing. Is there a library that I can use that does this kind of thing (plus possibly other related things) for me.
(I know that JS isn't mulithreaded.)
The jQuery Deferred/Promise methods do exactly this.
http://api.jquery.com/category/deferred-object/
精彩评论