Last active
February 14, 2022 13:31
-
-
Save Ericnr/a061acff217e15f7b387c64d1dc5a4c3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const makeQueue = limit => { | |
| const queue = []; | |
| let concurrency = 0; | |
| function enqueue(asyncFn) { | |
| if (concurrency < limit) { | |
| let curPromise = asyncFn().finally(() => { | |
| concurrency -= 1; | |
| const next = queue.shift(); | |
| if (next) { | |
| enqueue(next); | |
| } | |
| }); | |
| concurrency += 1; | |
| return curPromise; | |
| } else { | |
| const curPromise = new Promise((resolve, reject) => { | |
| queue.push(() => | |
| asyncFn() | |
| .then(result => resolve(result)) | |
| .catch(err => reject(err)) | |
| ); | |
| }); | |
| return curPromise; | |
| } | |
| } | |
| function batch(asyncFns) { | |
| return asyncFns.map(fn => enqueue(fn)); | |
| } | |
| return { enqueue, batch }; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment