jhurliman / node-rate-limiter

A generic rate limiter for node.js. Useful for API clients, web crawling, or other tasks that need to be throttled
MIT License
1.5k stars 132 forks source link

[Feature Request] Add a way to await "previous consumed tokens" #82

Open yaquawa opened 3 years ago

yaquawa commented 3 years ago

Hi, thanks for your efforts to this lib.

I have a use case where I don't know the actually value of amount for giving to removeTokens method until I've sent the request(AWS DynamoDB in my case).

Here is the pseudo code to explain what I mean:

let previousConsumedTokens = 0

async function foo(){
  for(let i = 0; i<10 ; i++) {
     await bucket.removeTokens(previousConsumedTokens)
     previousConsumedTokens = await sendRequest()
  }
}

foo() // run only one time will work

// call `foo` multiple times may not work,
// because the `previousConsumedTokens` may not be the "real" previousConsumedTokens.
foo() 

So the API may looks like this:

async function foo(){
  for(let i = 0; i<10 ; i++) {
     await bucket.removePrevTokens()
     previousConsumedTokens = await sendRequest()
     bucket.addPrevTokens(previousConsumedTokens)
  }
}

if you are OK for this feature request, I can send a PR for this, what do you think?