-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
48 lines (40 loc) · 1.11 KB
/
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
41
42
43
44
45
46
47
48
module.exports = function() {
// Listeners for completion.
var afters = [];
// Pending tasks, one of which is the `end()` call.
var pending = 1;
// Error sent to afters, if any.
var firstError = null;
// The task queueing function.
function wait(fn) {
pending++;
if (fn) return fn(callback);
else return callback;
}
// The task callback function.
function callback(err) {
pending--;
if (err && !firstError) firstError = err;
flush();
}
// Install callback after completion of all tasks.
wait.after = function(cb) {
afters.push(cb);
flush();
};
// Call once all tasks have started. (ie. following `emit()`)
wait.end = function(cb) {
if (cb) wait.after(cb);
callback();
};
// Helper that flushes errors and completion.
function flush() {
if (firstError === null && pending !== 0) return;
var list = afters;
afters = [];
var num = list.length;
for (var i = 0; i < num; i++)
list[i](firstError);
}
return wait;
};