UNPKG

limiter

Version:

A generic rate limiter for the web and node.js. Useful for API clients, web crawling, or other tasks that need to be throttled

18 lines (16 loc) 473 B
/** Serialize waiting requests so a backlog needs only one active timer. */ export class RequestQueue { private tail?: Promise<void>; run<T>(request: () => Promise<T>): Promise<T> { const result = this.tail ? this.tail.then(request) : request(); const tail = result.then( () => undefined, () => undefined, ); this.tail = tail; void tail.then(() => { if (this.tail === tail) this.tail = undefined; }); return result; } }