| 35 | } |
| 36 | |
| 37 | function limitConcurrency(fn, concurrency) { |
| 38 | const tokens = []; |
| 39 | const processing = new Set(); |
| 40 | async function getToken() { |
| 41 | const token = defer(); |
| 42 | tokens.push(token); |
| 43 | check(); |
| 44 | await token.promise; |
| 45 | return token; |
| 46 | } |
| 47 | function releaseToken(token) { |
| 48 | processing.delete(token); |
| 49 | check(); |
| 50 | } |
| 51 | function check() { |
| 52 | while (tokens.length && processing.size < concurrency) { |
| 53 | const token = tokens.shift(); |
| 54 | processing.add(token); |
| 55 | token.resolve(); |
| 56 | } |
| 57 | } |
| 58 | async function limited(...args) { |
| 59 | const token = await getToken(); |
| 60 | try { |
| 61 | return await fn(...args); |
| 62 | } finally { |
| 63 | releaseToken(token); |
| 64 | } |
| 65 | } |
| 66 | return limited; |
| 67 | } |
| 68 | |
| 69 | async function doRequest(path, options) { |
| 70 | options = { |