-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
pending.js
62 lines (54 loc) · 1.1 KB
/
pending.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// SPDX-FileCopyrightText: 2023 the cable-client authors
//
// SPDX-License-Identifier: AGPL-3.0-or-later
const EventEmitter = require("events").EventEmitter
const debug = require("debug")("pending")
const WAITING = 0
const READY = 1
class Pender extends EventEmitter {
constructor() {
super()
this.pending = 0
this.state = WAITING
this.queue = []
}
enqueue(cb) {
switch (this.state) {
case WAITING:
this.queue.push(cb)
break
case READY:
cb()
break
}
}
_done() {
debug("pender is done, emitting ready")
this.queue.forEach(cb => cb())
this.state = READY
this.emit("ready")
}
wait(msg) {
++this.pending
if (msg) {
debug("wait (%d) %s", this.pending, msg)
} else {
debug("wait (%d)", this.pending)
}
return () => {
this.proceed(msg)
}
}
proceed(msg) {
--this.pending
if (msg) {
debug("proceed (%d) %s", this.pending, msg)
} else {
debug("proceed (%d)", this.pending)
}
if (this.pending <= 0) {
this._done()
}
}
}
module.exports = Pender