-
Notifications
You must be signed in to change notification settings - Fork 1
/
channel.js
41 lines (37 loc) · 944 Bytes
/
channel.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
class Channel {
constructor() {
this.queue = []
this.pending = []
}
take = async () => {
if (this.queue.length == 0) {
const p = this.createPromise();
this.pending.push(p)
return await p.promise
} else {
const p = this.queue.shift()
p.resolve(p.value)
return await p.promise
}
}
put = async (value) => {
if (this.pending.length == 0) {
const p = this.createPromise()
p.value = value;
this.queue.push(p)
return p.promise
} else {
const p = this.pending.shift();
p.resolve(value)
}
}
createPromise = () => {
const p = {}
p.promise = new Promise((resolve, reject) => {
p.resolve = resolve;
p.reject = reject;
})
return p
}
}
export default Channel