Promise Throttle
This small (~530B minified and compressed) dependency-free library limits promises run per unit of time. Useful for Rest API consumption, which is normally rate-limited to a certain number of requests in a set amount of time.
On Node.js, pass the Promise library you are using to the constructor.
To use, simply add functions to the PromiseThrottle
that, once called, return a Promise
.
Use
The library can be used either server-side or in the browser.
var PromiseThrottle = ; /** * A function that once called returns a promise * @return Promise */ var { return { // here we simulate that the promise runs some code // asynchronously ; }; }; var promiseThrottle = requestsPerSecond: 1 // up to 1 request per second promiseImplementation: Promise // the Promise library you are using ; var amountOfPromises = 10; while amountOfPromises-- > 0 promiseThrottle ; // example using Promise.all var one = promiseThrottle; var two = promiseThrottle; var three = promiseThrottle; Promiseallone two three ;
Options
weight
You can specify weight
option for each promise to dynamically adjust throttling depending on
action "heaviness". For example, action with weight = 2
will be throttled as two regular actions. By default weight of all actions is 1.
var regularAction = promiseThrottle; var heavyAction = promiseThrottle;
signal
You can cancel queued promises using an AbortSignal. For this, pass a signal
option obtained from an AbortController
. Once it is aborted, the promises queued using the signal will be rejected.
If the environment where you are running the code doesn't support AbortController, you can use a polyfill.
var controller = ; var signal = controllersignal; var pt = ; pt; ... // let's abort the promises controller;
You can decide to make only specific promises abortable:
var controller = ; var signal = controllersignal; var pt = ; pt; pt; pt; ... // let's abort the second one controller;
When aborting, the promise returned by add
or addAll
is rejected with a specific error:
var controller = ; var signal = controllersignal; var pt = ; pt; ... // let's abort the promises controller;
Installation
For node.js, install the module with: npm i promise-throttle
If you are using it in a browser, you can use bower: bower install promise-throttle
Development
Install the dependencies using npm install
.
Run npm start
to lint, test and browserify promise-thottle.
Projects using it
See how some projects are using it:
- ivasilov/promised-twitter
- JMPerez/spotify-dedup
- johannesss/randify
- JoseBarrios/mturk-api
- zackiles/lucy-bot
License
MIT