-
Notifications
You must be signed in to change notification settings - Fork 1
/
test-10.js
64 lines (53 loc) · 1.28 KB
/
test-10.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
'use strict'
const tap = require('tap')
const Channel = require('./')
function uid () {
return Buffer.from(Math.random().toString(35).substr(2, 16))
}
tap.test('async iteration', async (t) => {
const channel = new Channel()
channel.give(1)
channel.give(2)
channel.close()
let i = 0
for await (let result of channel) {
t.equal(++i, result, `result is ${i}`)
}
t.equal(i, 2, `received ${i} items`)
t.end()
})
function delay (ms) {
return new Promise((resolve, reject) => setTimeout(resolve, ms))
}
tap.test('backpressure', async (t) => {
const channel = new Channel()
let requesting = true
const items = []
const n = 5
for (let i = 0; i < n; i++) {
const value = uid()
items.push(value)
}
async function produce () {
for (let value of items) {
requesting = false
await channel.give(value)
t.equal(requesting, true, 'should be waiting for data')
}
channel.close()
}
async function consume () {
let i = 0
for await (let value of channel) {
const expected = items[i++]
t.deepEqual(value, expected, 'received the expected value')
await delay(1000)
requesting = true
}
t.equal(i, n, 'received as many items as were sent')
}
await Promise.all([
produce(),
consume()
])
})