-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path04-select-take-send.js
71 lines (58 loc) · 1.44 KB
/
04-select-take-send.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
63
64
65
66
67
68
69
70
71
import chan from '../../src'
import {p, sleep} from '../utils'
async function producer(ch, items) {
p(` -> started producing into ${ ch }`)
for (let item of items) {
if (ch.canSend) {
p(` -> sending: ${ item }...`)
await ch.send(item)
} else {
p(` -> chan ${ch} closed`)
return
}
}
p(` -> finished producing into ${ ch }`)
}
async function consumer(ch, n = Number.MAX_SAFE_INTEGER) {
p(`<- started consuming from ${ ch }`)
let i = 0
while (++i <= n && ch.CLOSED != await ch.take()) {
p(`<- got:`, ch.value)
}
if (i > n) {
p(`<- consumed max of ${n} items`)
} else {
p(`<- chan closed`)
}
}
async function worker(chIn, chOut) {
let i = 1; while (true) {
switch (await chan.select( chIn.take(), chOut.send(i) )) {
case chIn:
p(`... received from ${ chIn }: ${ chIn.value }`)
break
case chOut:
p(`... sent to ${ chOut }: ${i}`)
++i
break
case chan.CLOSED:
p(`... both chIn and chOut have closed`)
return
}
}
}
async function run() {
//
// [producer]>--A-->[worker]>--B-->[consumer]
//
let chA = chan(0).named('A')
let chB = chan(0).named('B')
worker(chA, chB).catch(p)
producer(chA, [ 'X', 'Y', 'Z', 'P', 'Q' ]).catch(p)
consumer(chB, 5).catch(p)
await sleep(500)
p(`--- closing both channels...`)
await Promise.all([ chA.close(), chB.close() ])
p(`--- done`)
}
run().catch(p)