UNPKG

p-queue

Version:

Promise queue with concurrency control

365 lines (303 loc) • 13.6 kB
import { type Queue, type RunFunction } from './queue.js'; import PriorityQueue from './priority-queue.js'; import { type QueueAddOptions, type Options, type TaskOptions } from './options.js'; type Task<TaskResultType> = (options: TaskOptions) => TaskResultType | PromiseLike<TaskResultType>; type TaskResults<Tasks extends ReadonlyArray<Task<unknown>>> = { -readonly [Index in keyof Tasks]: Awaited<ReturnType<Tasks[Index]>>; }; type EventMap = { active: Event; idle: Event; empty: Event; add: Event; next: Event; completed: CustomEvent<unknown>; error: CustomEvent<unknown>; pendingZero: Event; rateLimit: Event; rateLimitCleared: Event; }; type EventName = keyof EventMap; type QueueEventListener<Name extends EventName> = ((event: EventMap[Name]) => void) | { handleEvent(event: EventMap[Name]): void; }; /** Promise queue with concurrency control. The queue is an `EventTarget`. Listen with `queue.addEventListener(event, listener)`, and stop with `queue.removeEventListener(event, listener)`. The options `{once: true}` and `{signal}` work too. The `completed` and `error` events have the result or the error in `event.detail`. If the result or the error is `undefined`, `event.detail` is `null`, because `CustomEvent` works that way. */ export default class PQueue<QueueType extends Queue<RunFunction, EnqueueOptionsType> = PriorityQueue, EnqueueOptionsType extends QueueAddOptions = QueueAddOptions> extends EventTarget { #private; constructor(options?: Options<QueueType, EnqueueOptionsType>); /** Get or set the default timeout. A change applies to tasks added after it. @example ``` const queue = new PQueue({timeout: 5000}); queue.timeout = 10000; ``` */ get timeout(): number | undefined; set timeout(timeout: number | undefined); get concurrency(): number; set concurrency(newConcurrency: number); /** Changes the priority of a waiting task, found by its `id`. Throws a `ReferenceError` if no waiting task has that `id`, for example because it already started. Throws a `TypeError` if `priority` is not a finite number. Tasks only wait when the queue has a `concurrency` limit, is paused, or is rate-limited. @example ``` // Raise the priority to run a task earlier import PQueue from 'p-queue'; const queue = new PQueue({concurrency: 1}); queue.add(async () => '🦄', {priority: 1}); queue.add(async () => '🦀', {priority: 0, id: '🦀'}); queue.add(async () => '🦄', {priority: 1}); queue.add(async () => '🦄', {priority: 1}); queue.setPriority('🦀', 2); // '🦀' runs second ``` @example ``` // Lower the priority to run a task later import PQueue from 'p-queue'; const queue = new PQueue({concurrency: 1}); queue.add(async () => '🦄', {priority: 1}); queue.add(async () => '🦀', {priority: 1, id: '🦀'}); queue.add(async () => '🦄'); queue.add(async () => '🦄', {priority: 0}); queue.setPriority('🦀', -1); // '🦀' runs last ``` */ setPriority(id: string, priority: number): void; /** Adds a sync or async task to the queue. Returns a promise that settles with the result of `fn` when the task completes, not when it is added. The function gets `{signal}` as its first argument. The signal is set when the task has a `signal` or a `timeout`, and aborts when either one does. Pass it on, for example to `fetch()`, to stop the work. The function runs in the async context of the `.add()` call (in Node.js 22.3 and later, Deno, and Bun), so it sees the [`AsyncLocalStorage`](https://nodejs.org/api/async_context.html#class-asynclocalstorage) values of the caller, also when it starts later. If you `await` each `.add()` call before the next, the tasks run one after the other, whatever the `concurrency`. Handle rejections of the returned promise. Otherwise, they are unhandled rejections, which can make the process exit. */ add<TaskResultType>(function_: Task<TaskResultType>, options?: Partial<EnqueueOptionsType>): Promise<Awaited<TaskResultType>>; /** Like `.add()`, but takes an array of functions. @returns A promise that resolves with all the results, in the order of the functions, when all tasks complete. */ addAll<const Tasks extends ReadonlyArray<Task<unknown>>>(functions: Tasks, options?: Partial<EnqueueOptionsType>): Promise<TaskResults<Tasks>>; addAll<TaskResultsType>(functions: ReadonlyArray<Task<TaskResultsType>>, options?: Partial<EnqueueOptionsType>): Promise<Array<Awaited<TaskResultsType>>>; /** Starts (or resumes) running queued tasks. Only needed if the queue is paused, with `autoStart: false` or `.pause()`. @returns `this` (the instance). */ start(): this; /** Stops starting new tasks. Running tasks continue. */ pause(): void; /** Removes all waiting tasks. Running tasks continue. The promises returned by `.add()` for the removed tasks reject with an `AbortError`, which is a `DOMException`. The removed tasks do not run, and they do not emit the `error` event. If you ignore such a promise, its rejection is not reported as unhandled. This does not apply to a promise made from it, like the one from `queue.add(fn).then(…)` or from `.addAll()`, so handle the rejection of that promise. @example ``` import PQueue from 'p-queue'; const queue = new PQueue({concurrency: 1}); queue.add(() => doWork()); const promise = queue.add(() => doWork()); queue.clear(); try { await promise; } catch (error) { console.log(error.name); //=> 'AbortError' } ``` */ clear(): void; /** Returns a promise that resolves when the queue is empty. Tasks can still be running. The promise resolves once. Call `.onEmpty()` again to wait for the next time, or use the `empty` event to get every time. */ onEmpty(): Promise<void>; /** Returns a promise that resolves when `queue.size < limit`. Await it before you add a task, to keep the queue from growing beyond a size. It counts only waiting tasks, not running tasks. */ onSizeLessThan(limit: number): Promise<void>; /** Returns a promise that resolves when the queue is empty and all tasks have completed: `queue.size === 0 && queue.pending === 0`. Unlike `.onEmpty()`, it waits for running tasks to finish. The promise resolves once. Call `.onIdle()` again to wait for the next time, or use the `idle` event to get every time. */ onIdle(): Promise<void>; /** Returns a promise that resolves when no tasks are running: `queue.pending === 0`. Unlike `.onIdle()`, it ignores queued tasks. Use it to let running tasks finish before you change shared state. A task that timed out, or whose `signal` aborted while it ran, no longer counts, although its function can still run. @example ``` queue.pause(); await queue.onPendingZero(); // No tasks are running, but the queue can still have tasks ``` */ onPendingZero(): Promise<void>; /** Returns a promise that resolves when the queue becomes rate-limited by `intervalCap`. If the queue is already rate-limited, it resolves immediately. Useful for backpressure, when tasks are added faster than they run. @example ``` const queue = new PQueue({intervalCap: 5, interval: 1000}); for (let index = 0; index < 10; index++) { queue.add(() => someTask()); } await queue.onRateLimit(); console.log('The queue is rate-limited'); ``` */ onRateLimit(): Promise<void>; /** Returns a promise that resolves when the queue is no longer rate-limited. If the queue is not rate-limited, it resolves immediately. @example ``` const queue = new PQueue({intervalCap: 5, interval: 1000}); for (let index = 0; index < 10; index++) { queue.add(() => someTask()); } await queue.onRateLimitCleared(); console.log('The rate limit is cleared'); ``` */ onRateLimitCleared(): Promise<void>; /** Returns a promise that rejects when a task fails: it throws, times out, or its `signal` aborts while it runs. It rejects with the error of the task, or with `null` if the error is `undefined`, like the `error` event. Use `Promise.race([queue.onError(), queue.onIdle()])` to stop at the first error, and to resolve normally when the queue becomes idle. Each call adds an `error` listener that stays until a task fails, so to get every error, for example in a loop, use the `error` event instead. Important: The promises returned by `.add()` still reject. Handle each of them (for example with `.catch(() => {})`) to prevent unhandled rejections. @example ``` import PQueue from 'p-queue'; const queue = new PQueue({concurrency: 2}); // Do not start the remaining tasks. Pause in an `error` listener, because it runs before the next task starts, and the code after `await` runs later. queue.addEventListener('error', () => { queue.pause(); }, {once: true}); queue.add(() => fetchData(1)).catch(() => {}); queue.add(() => fetchData(2)).catch(() => {}); queue.add(() => fetchData(3)).catch(() => {}); try { await Promise.race([ queue.onError(), queue.onIdle() ]); } catch (error) { console.error('Queue failed:', error); } ``` */ onError(): Promise<never>; /** The number of tasks waiting to run. */ get size(): number; /** The number of waiting tasks with the given `priority`. @example ``` import PQueue from 'p-queue'; const queue = new PQueue(); // Paused, so the tasks stay queued. Without it they all start synchronously and the queue is empty by the time `sizeBy` reads it. queue.pause(); queue.add(async () => '🦄', {priority: 1}); queue.add(async () => '🦄', {priority: 0}); queue.add(async () => '🦄', {priority: 1}); console.log(queue.sizeBy({priority: 1})); //=> 2 console.log(queue.sizeBy({priority: 0})); //=> 1 ``` */ sizeBy(options: Readonly<Partial<EnqueueOptionsType>>): number; /** The number of running tasks. */ get pending(): number; /** Whether the queue is paused. */ get isPaused(): boolean; /** Whether the queue is rate-limited: the number of tasks started in the current interval, plus the tasks still running from earlier intervals with `carryoverIntervalCount`, has reached `intervalCap`, and tasks are waiting. */ get isRateLimited(): boolean; /** Whether tasks are waiting because all concurrency slots are in use, or because the queue is rate-limited. Useful to detect backpressure and tasks that hang. @example ``` import PQueue from 'p-queue'; const queue = new PQueue({concurrency: 2}); // Backpressure if (queue.isSaturated) { await queue.onSizeLessThan(queue.concurrency); } // Monitoring setInterval(() => { if (queue.isSaturated) { console.warn(`Queue saturated: ${queue.pending} running, ${queue.size} waiting`); } }, 60000); ``` */ get isSaturated(): boolean; /** An array with the running tasks. Each task has its `id`, `priority`, `startTime`, `timeout`, and `timeoutRemaining` (the milliseconds until it times out). Without a timeout, `timeout` and `timeoutRemaining` are `undefined`. @example ``` import PQueue from 'p-queue'; const queue = new PQueue({concurrency: 2, timeout: 10000}); queue.add(() => fetchUser(123), {id: 'user-123'}); queue.add(() => fetchPosts(456), {id: 'posts-456', priority: 1}); console.log(queue.runningTasks); // => [{ // id: 'user-123', // priority: 0, // startTime: 1759253001716, // timeout: 10000, // timeoutRemaining: 10000 // }, { // id: 'posts-456', // priority: 1, // startTime: 1759253001716, // timeout: 10000, // timeoutRemaining: 10000 // }] ``` */ get runningTasks(): ReadonlyArray<{ readonly id: string; readonly priority: number; readonly startTime: number; readonly timeout: number | undefined; readonly timeoutRemaining: number | undefined; }>; } /** The error a task rejects with when it times out. It is a `DOMException` named `TimeoutError`, like the error of `AbortSignal.timeout()`. @example ``` import PQueue, {TimeoutError} from 'p-queue'; const queue = new PQueue({timeout: 1000}); try { await queue.add(() => someTask()); } catch (error) { if (error instanceof TimeoutError) { console.log('Task timed out'); } } ``` */ export declare class TimeoutError extends DOMException { constructor(message?: string); } export type { Queue, RunFunction } from './queue.js'; export { default as PriorityQueue } from './priority-queue.js'; export { type QueueAddOptions, type Options, type TaskOptions } from './options.js'; export default interface PQueue<QueueType extends Queue<RunFunction, EnqueueOptionsType> = PriorityQueue, EnqueueOptionsType extends QueueAddOptions = QueueAddOptions> { addEventListener<Name extends EventName>(type: Name, listener: QueueEventListener<Name>, options?: boolean | AddEventListenerOptions): void; removeEventListener<Name extends EventName>(type: Name, listener: QueueEventListener<Name>, options?: boolean | EventListenerOptions): void; }