oxedyne/fe2o3/fe2o3_text/tests/detect_corpus/js/async_await.txt
1.6 KiB, 1 run
created by r1870400018:11998, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | class TaskRunner { |
| 2 | constructor(concurrency = 4) { |
| 3 | this.concurrency = concurrency; |
| 4 | this.queue = []; |
| 5 | this.running = 0; |
| 6 | this.results = []; |
| 7 | } |
| 8 | |
| 9 | add(asyncFn) { |
| 10 | return new Promise((resolve, reject) => { |
| 11 | this.queue.push({ fn: asyncFn, resolve, reject }); |
| 12 | this._run(); |
| 13 | }); |
| 14 | } |
| 15 | |
| 16 | async _run() { |
| 17 | while (this.running < this.concurrency && this.queue.length > 0) { |
| 18 | const { fn, resolve, reject } = this.queue.shift(); |
| 19 | this.running++; |
| 20 | try { |
| 21 | const result = await fn(); |
| 22 | this.results.push(result); |
| 23 | resolve(result); |
| 24 | } catch (err) { |
| 25 | reject(err); |
| 26 | } finally { |
| 27 | this.running--; |
| 28 | this._run(); |
| 29 | } |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | async drain() { |
| 34 | while (this.queue.length > 0 || this.running > 0) { |
| 35 | await new Promise((r) => setTimeout(r, 10)); |
| 36 | } |
| 37 | return this.results; |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | async function fetchWithRetry(url, retries = 3) { |
| 42 | for (let attempt = 1; attempt <= retries; attempt++) { |
| 43 | try { |
| 44 | const response = await fetch(url); |
| 45 | if (!response.ok) { |
| 46 | throw new Error(`HTTP ${response.status}`); |
| 47 | } |
| 48 | return await response.json(); |
| 49 | } catch (err) { |
| 50 | if (attempt === retries) throw err; |
| 51 | const delay = Math.pow(2, attempt) * 100; |
| 52 | await new Promise((r) => setTimeout(r, delay)); |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | export { TaskRunner, fetchWithRetry }; |