Skip to content

Instantly share code, notes, and snippets.

@Ericnr
Last active February 14, 2022 13:31
Show Gist options
  • Select an option

  • Save Ericnr/a061acff217e15f7b387c64d1dc5a4c3 to your computer and use it in GitHub Desktop.

Select an option

Save Ericnr/a061acff217e15f7b387c64d1dc5a4c3 to your computer and use it in GitHub Desktop.
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