Join
Joins any number of asynchronous calls together -
similar to how pthread_join
works for C threads
and when()
works for Q-style promises.
It's basically a callback counter that lets you know when everything is done.
Installation
Node.JS (Server):
npm install join
Browser:
You can install from bower:
bower install join
Or download the raw file from https://raw.github.com/FuturesJS/join/master/join.js:
wget https://raw.github.com/FuturesJS/join/master/join.js
Browser Usage
; { 'use strict'; var join = windowJoin ; // Use `join.add()` in place of a callback function ; ; ; // Use `join.notify()` for incremental updates join; // Use `join.then(cb)` to fire `cb` when all of the `join.add()` callbacks have been called. join;};
Node.js Usage
'use strict'; var request = Join = Join join = Join ; // Use `join.add()` in place of a callback functionrequest;request;request; // Use `join.notify()` for incremental updatesjoin; // Use `join.then(cb)` to fire `cb` when all of the `join.add()` callbacks have been called.join;
API
Join
join = Join.create(defaultContext=null)
- create a Join that will count callbacksjoin.add()
- creates a joinable callback that you can throw aroundjoin.notify(progressCallback, context=null)
join.then(finalCallback, context=null)
- Fires
finalCallback
when all joined callbacks have completed - Must be called after the last
add()
- Fires
join.length
- the number of timesjoin.add()
has been called
Potential Gotchas
Order matters
The arguments to join.then(cb)
are in the order that the join.add()
were called.
callbackA = join; callbackB = join; ; ; join;
Callback within a callback
If you handle the join callback inside of another callback then you'll need to place the join callback in the parent scope.
Fails:
request; ; join;
Works as expected:
request; bingCallback = join ;
this
ness
Losing Fails:
// `doStuff` loses the `this` binding to `myObject` join;
Works as expected:
// `doStuff` retains the `this` binding
join.then(myObject.doStuff, myObject);
Also works as expected:
// `doStuff` retains the `this` binding
join.then(function (argsA, argsB, argsC) {
myObject.doStuff(argsA, argsB, argsC);
});