Priority & wrapping

Run important jobs first and wrap existing functions.

Priority & wrapping

Priority

Higher-priority jobs run first. Lower number = higher priority (e.g. Priority.CRITICAL = 0 runs before Priority.NORMAL = 5). Use the Priority enum or any number.

import { RateLimiter, Priority } from 'rate-queue';

const limiter = new RateLimiter({ maxConcurrent: 1 });

limiter.schedule({ priority: Priority.LOW }, () => backgroundSync());
limiter.schedule({ priority: Priority.CRITICAL }, () => handleUrgentRequest());
// Critical runs before low when a slot is free.

Priority values: CRITICAL = 0, HIGH = 3, NORMAL = 5, LOW = 7, IDLE = 9.

Wrapping a function

Turn any async function into a rate-limited one with limiter.wrap(fn). You get a new function with the same signature; each call goes through the limiter.

// Your existing async function
async function getUser(id) {
  const res = await fetch(`https://api.example.com/users/${id}`);
  return res.json();
}

// Rate-limited version — same args, same return
const limitedGetUser = limiter.wrap(getUser);

// Call it like normal; the limiter queues and paces the calls
const user1 = await limitedGetUser(1);
const user2 = await limitedGetUser(2);

With options (e.g. priority):

const limitedFetch = limiter.wrap(
  { priority: Priority.HIGH },
  async (url) => {
    const res = await fetch(url);
    return res.json();
  }
);

const data = await limitedFetch('https://api.example.com/users');

Next: Retry & cancellation.