-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWait.js
45 lines (38 loc) · 957 Bytes
/
Wait.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
/* Wait.js
poorly named module that keeps track of multiple async events and wait
for things to be complete before moving on.
Wait::start = Start to wait. if we're not waiting for anything, fire a "done" event.
Wait::for = Add a function to wait for. Will keep waiting until that function runs.
*/
var EventEmitter = require("events").EventEmitter;
function Wait(){
EventEmitter.call(this);
this.counter = 0;
this.ready = false;
}
Wait.prototype = {
__proto__: EventEmitter.prototype,
"for": function(func) {
var self = this;
self.counter++;
return function() {
try {
var ret = func.apply(this, arguments);
} finally {
self.counter--;
self.check();
return ret;
}
};
},
check: function() {
if (this.ready && !this.counter) {
this.emit("done");
}
},
start: function() {
this.ready = true;
this.check();
}
};
module.exports = Wait;