-
Notifications
You must be signed in to change notification settings - Fork 1
/
16-unidirectional.js
77 lines (72 loc) · 2 KB
/
16-unidirectional.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
72
73
74
75
76
77
import chan from '../../src'
import {p, sleep, getOneLinerBody} from '../utils'
async function produceInto(sendOnly) {
p()
p(`sendOnly.canTake:`, sendOnly.canTake)
p(`sendOnly.canSend:`, sendOnly.canSend)
//
// prohibited for send-only chan, will throw
//
await attempt(_ => sendOnly.take(), '\n')
await attempt(_ => sendOnly.takeSync())
await attempt(_ => sendOnly.takeOnly)
//
// allowed for send-only chan
//
await attempt(_ => sendOnly.send(123), '\n')
await attempt(_ => sendOnly.sendSync(456))
await attempt(_ => sendOnly.sendOnly)
async function close() {
await sleep(100)
await attempt(_ => sendOnly.close(), '\n')
await attempt(_ => sendOnly.closeSync())
await attempt(_ => sendOnly.closeNow())
}
// close asynchronously to avoid deadlock
close().catch(p)
}
async function consumeFrom(takeOnly) {
p()
p(`takeOnly.canTake:`, takeOnly.canTake)
p(`takeOnly.canSend:`, takeOnly.canSend)
//
// prohibited for take-only chan, will throw
//
await attempt(_ => takeOnly.send(123), '\n')
await attempt(_ => takeOnly.sendSync(456))
await attempt(_ => takeOnly.close())
await attempt(_ => takeOnly.closeSync())
await attempt(_ => takeOnly.closeNow())
await attempt(_ => takeOnly.sendOnly)
//
// allowed for take-only chan
//
await attempt(_ => takeOnly.take(), '\n')
await attempt(_ => takeOnly.takeSync())
await attempt(_ => takeOnly.takeOnly)
}
async function run() {
let ch = chan(2)
await produceInto(ch.sendOnly)
await consumeFrom(ch.takeOnly)
}
async function attempt(fn, prependDesc = '') {
let desc = prependDesc + getOneLinerBody(fn)
try {
let result = fn()
if (result && 'function' == typeof result.then) {
try {
result = await result
} catch (err) {
p(`${desc} failed asynchronously: ${err}`)
return
}
p(`${desc} succeeded asynchronously, result: ${result}`)
} else {
p(`${desc}: ${result}`)
}
} catch (err) {
p(`${desc} thrown ${err}`)
}
}
run().catch(p)