-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest.js
More file actions
108 lines (90 loc) · 2.37 KB
/
test.js
File metadata and controls
108 lines (90 loc) · 2.37 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
const sync = require('./index')
async function test(name, fn, timeout = 500) {
try {
if (timeout) {
let tid
await Promise.race([
new Promise((_resolve, reject) => {
tid = setTimeout(() => reject(new Error(`Timeout after ${timeout} ms`)), timeout)
}),
new Promise(resolve => resolve(fn())).then(
res => {
clearTimeout(tid)
},
err => {
clearTimeout(tid)
throw err
}),
])
} else {
await new Promise(resolve => resolve(fn()))
}
console.log(`[pass] ${name}`)
} catch(e) {
process.exitCode = 1
console.log(`[fail] ${name}: ${e.message}`)
console.log(e.stack)
}
}
test('Syncing two per usual', async () => {
const [first] = sync(2)
await Promise.all([first, first])
})
test('Interleaving unrelated promises', async () => {
const [ready, done] = sync(2)
const p1 = new Promise(async res => {
await ready
await new Promise(r => setImmediate(r))
await done
res()
})
const p2 = new Promise(async res => {
await new Promise(r => setImmediate(r))
await ready
await done
res()
})
await p1
await p2
})
test('Two different sync generators with different counts', async () => {
const [three] = sync(3)
const [two] = sync(2)
await Promise.all([two, two])
await Promise.all([three, three, three])
})
test('Never syncing', async () => {
const [two] = sync(2)
const result = await Promise.race([
two,
new Promise(resolve => setTimeout(() => resolve('timeout'), 10))
])
if (result !== 'timeout') {
throw new Error('Unexpected promise resolution')
}
})
test('Can be chained', async () => {
const [two] = sync()
const [foo, bar] = await Promise.all([two.then(() => 'foo'), two.then(() => 'bar')])
if (foo !== 'foo') {
throw new Error('Expected foo, got ' + foo)
}
if (bar !== 'bar') {
throw new Error('Expected bar, got ' + bar)
}
})
test('Oversyncing has no problems', async () => {
const [two] = sync()
await Promise.all([two, two, two])
})
test('Defaults to two', async () => {
const [twoA, twoB] = sync()
const result = await Promise.race([
twoA,
new Promise(resolve => setTimeout(() => resolve('timeout'), 10))
])
if (result !== 'timeout') {
throw new Error('Unexpected promise resolution')
}
await Promise.all([twoB, twoB])
})