-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
40 lines (33 loc) · 954 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
var once = require('once');
var isError = function(e) {
return Object.prototype.toString.call(e) === '[object Error]' || e instanceof Error;
};
module.exports = function(afterAllCb) {
afterAllCb = once(afterAllCb || function() {});
var errorMessage ='"next" function called after the final callback.'+
' Make sure all the calls to "next" are on the same tick';
var calls = 0;
var done = false;
var finalError = null;
process.nextTick(function() {
if (calls === 0) {
done = true;
afterAllCb();
}
});
return function next(cb) {
if (done) throw new Error(errorMessage);
calls++;
return function thecallback(err) {
var args = arguments;
if (isError(err) && !finalError) finalError = err;
process.nextTick(function() {
if (cb) cb.apply(null, args);
if (--calls === 0) {
done = true;
afterAllCb(finalError);
}
});
};
};
};