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.51k stars 135 forks source link

Is it possible to use async function as callback? #66

Closed duc-anh-tran closed 3 years ago

duc-anh-tran commented 4 years ago

I used await inside callMyRequestSendingFunction(...). Is it possible to use async function as callback? As I tried adding async,

while (morePagesAvailable) {
        let response:any = [];
        myRateLimiter.removeTokens(1, async function(err, remainingRequests) {
            response = await fetcher(url);     
       });

       // Add response to the list of responses
}
WangHansen commented 4 years ago

Just wrap the entire thing with promise:

    return new Promise((resolve, reject) => {
      limiter.removeTokens(1, (err: Error, remaining: number) => {
        if (err) reject(err);
        if (remaining < 0) {
          reject(new RateLimitError("Too many requests"));
        } else {
          fetcher().then(resolve);
        }
      });
    });