Skip to content

Instantly share code, notes, and snippets.

@ikibalnyi
Last active August 5, 2019 01:33
Show Gist options
  • Save ikibalnyi/7aed78f8162c778eedc58a80587f0f40 to your computer and use it in GitHub Desktop.
Save ikibalnyi/7aed78f8162c778eedc58a80587f0f40 to your computer and use it in GitHub Desktop.
Simple promise throttler function
const promiseThrottle = (maxParallelCalls = 10) => {
const queued = [];
let parallelCalls = 0;
const abortController = new AbortController();
const execute = () => {
if (!queued.length || parallelCalls >= maxParallelCalls) return;
const { promiseFn, resolve, reject } = queued.shift();
parallelCalls++;
if (abortController.signal.aborted) {
reject(new DOMException('', 'AbortError'));
queued.splice(0, queued.length);
} else {
promiseFn()
.then(resolve)
.catch(reject)
.then(() => {
parallelCalls--;
execute();
})
}
};
const add = (promiseFn) => {
return new Promise((resolve, reject) => {
queued.push({
resolve,
reject,
promiseFn
});
execute();
})
};
return { add, abort: () => abortController.abort() };
};
export default promiseThrottle;
import promiseThrottle from 'promiseThrottle';
const requestDeferreds = urls.map((url) => (
throttler.add(() =>
fetch(url)
)
));
Promise.all(requestDeferreds)
.then((data) => {
conosle.log(data)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment