xavi- / node-simple-rate-limiter

A simple way to rate limit how often a function is executed.
76 stars 10 forks source link

Support for Promises #10

Closed Stumblor closed 1 year ago

Stumblor commented 6 years ago

I've added an extra function in order to support the throttling of promises.

Example usage:

var limit = require("simple-rate-limiter");
var request = limit.promise(Some.Promise.Request).to(1).per(1000);
return request({ 
    OrderID: 666
}).then(result => {
    // done!
});

Or for multiple calls:

var limit = require("simple-rate-limiter");
var request = limit.promise(Some.Promise.Request).to(1).per(1000);
var items = [{ ID: 1 }, { ID: 2 }]
Promise.all(items.map(item => {
    return request({ 
        OrderID: item.ID
    }).then(result => {
        // do something with result
        return result;
    })
}))
.then(arrayOfResults => {
  // yay!
})
markstos commented 1 year ago

Now 6 years later, async/await and promises have taken over and callback style is rarely seen and best avoided.

Given that, I would suggest a breaking change to switch to the promise/async/await style completely and drop support for callbacks. If people want to use the new version with callback code, they can "promisify" the callback that they would pass in:

const limit = require("simple-rate-limiter");
const result = await limit(
   request({ OrderID: }) // Promise
).to(1).per(1000);
xavi- commented 1 year ago

Makes sense! Thank you for the PR

xavi- commented 1 year ago

@markstos I don't think I'll change the default behavior, but I like the idea of exposing this type of functionality through limiter.promise

xavi- commented 1 year ago

Okay, I changed the implementations and api a bit. Here's an example usage:

const promiser = num => new Promise(resolve => resolve(num * 2));
const limited = limit.promise(promiser).to(5).per(1000);

const numbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ];
const doubled = await Promise.all(numbers.map(num => limited(num)));

assert.deepEqual(doubled, [ 2, 4, 6, 8, 10, 12, 14, 16, 18 ]);

Update published in 0.5.0

markstos commented 1 year ago

Thanks!

It would be helpful if a changelog were published so people could easily understand if it was safe and useful to upgrade. The easiest way to do this now is to use Github Releases feature. I use gh release create to make releases with documented changes.

The tool these days even helps write the Changelog:

https://cli.github.com/