-
Notifications
You must be signed in to change notification settings - Fork 2
/
worker.js
32 lines (32 loc) · 986 Bytes
/
worker.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
class DownloadStream extends ReadableStream {
constructor(requests, strategy = { highWaterMark: 3 }) {
const promises = []
const controller = new AbortController()
const iterator = 'next' in requests ? requests
: requests[Symbol.iterator in requests ? Symbol.iterator : Symbol.asyncIterator]()
super({
async pull(ctrl) {
let i = ctrl.desiredSize - promises.length
while (i--) {
const { done, value } = await iterator.next()
if (done) break
const promise = fetch(value, { signal: controller.signal })
promises.push(promise)
}
if (promises.length) ctrl.enqueue(await promises.shift())
else ctrl.close()
},
cancel(e) {
controller.abort(e)
iterator.throw?.(e)
}
}, strategy)
}
[Symbol.asyncIterator]() {
const reader = this.getReader()
return {
next() { return reader.read() },
throw(e) { reader.cancel(e) }
}
}
}