Last active
August 5, 2019 01:33
-
-
Save ikibalnyi/7aed78f8162c778eedc58a80587f0f40 to your computer and use it in GitHub Desktop.
Simple promise throttler function
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 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; |
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
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