-
Notifications
You must be signed in to change notification settings - Fork 18
/
index.ts
230 lines (202 loc) · 4.96 KB
/
index.ts
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
/**
* @packageDocumentation
*
* Takes an (async) iterable that emits promise-returning functions, invokes them in parallel up to the concurrency limit and emits the results as they become available, optionally in the same order as the input
*
* @example
*
* ```javascript
* import parallel from 'it-parallel'
* import all from 'it-all'
* import delay from 'delay'
*
* // This can also be an iterator, async iterator, generator, etc
* const input = [
* async () => {
* console.info('start 1')
* await delay(500)
*
* console.info('end 1')
* return 1
* },
* async () => {
* console.info('start 2')
* await delay(200)
*
* console.info('end 2')
* return 2
* },
* async () => {
* console.info('start 3')
* await delay(100)
*
* console.info('end 3')
* return 3
* }
* ]
*
* const result = await all(parallel(input, {
* concurrency: 2
* }))
*
* // output:
* // start 1
* // start 2
* // end 2
* // start 3
* // end 3
* // end 1
*
* console.info(result) // [2, 3, 1]
* ```
*
* If order is important, pass `ordered: true` as an option:
*
* ```javascript
* const result = await all(parallel(input, {
* concurrency: 2,
* ordered: true
* }))
*
* // output:
* // start 1
* // start 2
* // end 2
* // start 3
* // end 3
* // end 1
*
* console.info(result) // [1, 2, 3]
* ```
*/
import defer from 'p-defer'
interface Operation<T> {
done: boolean
ok: boolean
err: Error
value: T
}
const CustomEvent = globalThis.CustomEvent ?? Event
export interface ParallelOptions {
/**
* How many jobs to execute in parallel (default: )
*/
concurrency?: number
ordered?: boolean
}
/**
* Takes an (async) iterator that emits promise-returning functions,
* invokes them in parallel and emits the results as they become available but
* in the same order as the input
*/
export default async function * parallel <T> (source: Iterable<() => Promise<T>> | AsyncIterable<() => Promise<T>>, options: ParallelOptions = {}): AsyncGenerator<T, void, undefined> {
let concurrency = options.concurrency ?? Infinity
if (concurrency < 1) {
concurrency = Infinity
}
const ordered = options.ordered == null ? false : options.ordered
const emitter = new EventTarget()
const ops: Array<Operation<T>> = []
let slotAvailable = defer()
let resultAvailable = defer()
let sourceFinished = false
let sourceErr: Error | undefined
let opErred = false
emitter.addEventListener('task-complete', () => {
resultAvailable.resolve()
})
void Promise.resolve().then(async () => {
try {
for await (const task of source) {
if (ops.length === concurrency) {
slotAvailable = defer()
await slotAvailable.promise
}
if (opErred) {
break
}
const op: any = {
done: false
}
ops.push(op)
task()
.then(result => {
op.done = true
op.ok = true
op.value = result
emitter.dispatchEvent(new CustomEvent('task-complete'))
}, err => {
op.done = true
op.err = err
emitter.dispatchEvent(new CustomEvent('task-complete'))
})
}
sourceFinished = true
emitter.dispatchEvent(new CustomEvent('task-complete'))
} catch (err: any) {
sourceErr = err
emitter.dispatchEvent(new CustomEvent('task-complete'))
}
})
function valuesAvailable (): boolean {
if (ordered) {
return ops[0]?.done
}
return Boolean(ops.find(op => op.done))
}
function * yieldOrderedValues (): Generator<T, void, unknown> {
while ((ops.length > 0) && ops[0].done) {
const op = ops[0]
ops.shift()
if (op.ok) {
yield op.value
} else {
// allow the source to exit
opErred = true
slotAvailable.resolve()
throw op.err
}
slotAvailable.resolve()
}
}
function * yieldUnOrderedValues (): Generator<T, void, unknown> {
// more values can become available while we wait for `yield`
// to return control to this function
while (valuesAvailable()) {
for (let i = 0; i < ops.length; i++) {
if (ops[i].done) {
const op = ops[i]
ops.splice(i, 1)
i--
if (op.ok) {
yield op.value
} else {
opErred = true
slotAvailable.resolve()
throw op.err
}
slotAvailable.resolve()
}
}
}
}
while (true) {
if (!valuesAvailable()) {
resultAvailable = defer()
await resultAvailable.promise
}
if (sourceErr != null) {
// the source threw an error, propagate it
throw sourceErr
}
if (ordered) {
yield * yieldOrderedValues()
} else {
yield * yieldUnOrderedValues()
}
if (sourceFinished && ops.length === 0) {
// not waiting for any results and no more tasks so we are done
break
}
}
}