p-queue
- Version 10.0.0
- Published
- 103 kB
- No dependencies
- MIT license
Install
npm i p-queueyarn add p-queuepnpm add p-queueOverview
Promise queue with concurrency control
Index
Classes
class PQueue
class PQueue< QueueType extends Queue<RunFunction, EnqueueOptionsType> = PriorityQueue, EnqueueOptionsType extends QueueAddOptions = QueueAddOptions> extends EventTarget {}Promise queue with concurrency control.
The queue is an
EventTarget. Listen withqueue.addEventListener(event, listener), and stop withqueue.removeEventListener(event, listener). The options{once: true}and{signal}work too. Thecompletedanderrorevents have the result or the error inevent.detail. If the result or the error isundefined,event.detailisnull, becauseCustomEventworks that way.
constructor
constructor(options?: Options<QueueType, EnqueueOptionsType>);property concurrency
concurrency: number;property Tasks
Tasks: any;property timeout
timeout: number;Get or set the default timeout. A change applies to tasks added after it.
Example 1
``` const queue = new PQueue({timeout: 5000});
queue.timeout = 10000; ```
method add
add: <TaskResultType>( function_: Task<TaskResultType>, options?: Partial<EnqueueOptionsType>) => Promise<Awaited<TaskResultType>>;Adds a sync or async task to the queue.
Returns a promise that settles with the result of
fnwhen the task completes, not when it is added. The function gets{signal}as its first argument. The signal is set when the task has asignalor atimeout, and aborts when either one does. Pass it on, for example tofetch(), 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
awaiteach.add()call before the next, the tasks run one after the other, whatever theconcurrency.Handle rejections of the returned promise. Otherwise, they are unhandled rejections, which can make the process exit.
method addAll
addAll: () => any;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.
method ReadonlyArray
ReadonlyArray: <Task>() => any;method setPriority
setPriority: (id: string, priority: number) => void;Changes the priority of a waiting task, found by its
id. Throws aReferenceErrorif no waiting task has thatid, for example because it already started. Throws aTypeErrorifpriorityis not a finite number. Tasks only wait when the queue has aconcurrencylimit, is paused, or is rate-limited.Example 1
``` // 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 2
``` // 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 ```
class PriorityQueue
class PriorityQueue implements Queue<RunFunction, PriorityQueueOptions> {}property size
readonly size: number;method dequeue
dequeue: () => RunFunction | undefined;method enqueue
enqueue: (run: RunFunction, options?: Partial<PriorityQueueOptions>) => void;method filter
filter: (options: Readonly<Partial<PriorityQueueOptions>>) => RunFunction[];method remove
remove: { (id: string): void; (run: RunFunction): void };method setPriority
setPriority: (id: string, priority: number) => void;class TimeoutError
class TimeoutError extends DOMException {}The error a task rejects with when it times out. It is a
DOMExceptionnamedTimeoutError, like the error ofAbortSignal.timeout().Example 1
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');}}
constructor
constructor(message?: string);Interfaces
interface PQueue
interface PQueue< QueueType extends Queue<RunFunction, EnqueueOptionsType> = PriorityQueue, EnqueueOptionsType extends QueueAddOptions = QueueAddOptions> {}method addEventListener
addEventListener: <Name extends keyof EventMap>( type: Name, listener: QueueEventListener<Name>, options?: boolean | AddEventListenerOptions) => void;method removeEventListener
removeEventListener: <Name extends keyof EventMap>( type: Name, listener: QueueEventListener<Name>, options?: boolean | EventListenerOptions) => void;Type Aliases
type Options
type Options< QueueType extends Queue<RunFunction, QueueOptions> = PriorityQueue, QueueOptions extends QueueAddOptions = QueueAddOptions> = { /** The maximum number of tasks that run at the same time. Must be an integer or `Infinity`.
Minimum: `1`.
@default Infinity */ readonly concurrency?: number | undefined; /** Whether tasks start as soon as they are added. If `false`, call `.start()` to start them.
@default true */ readonly autoStart?: boolean | undefined; /** A class with `enqueue()`, `dequeue()`, `filter()`, `setPriority()`, and `remove()` methods and a `size` getter. See [Custom QueueClass](https://github.com/sindresorhus/p-queue#custom-queueclass). */ readonly queueClass?: (new () => QueueType) | undefined; /** The maximum number of tasks that start in each `interval`. Must be an integer or `Infinity`.
Minimum: `1`.
@default Infinity */ readonly intervalCap?: number | undefined; /** The length of the rate-limit interval in milliseconds. `0` disables rate limiting. The rate limit uses the system clock (`Date.now()`), so if the clock goes back, tasks can wait for as long as it went back.
Minimum: `0`. Maximum: `2147483647` (about 24.8 days) with a finite `intervalCap`, else any finite number.
@default 0 */ readonly interval?: number | undefined; /** Whether tasks that are still running when an interval ends count against `intervalCap` in the next interval.
@default false */ readonly carryoverIntervalCount?: boolean | undefined; /** Whether to rate limit with a sliding window instead of fixed windows. Requires a non-zero `interval` and a finite `intervalCap`.
With a sliding window, no more than `intervalCap` tasks start in any period of length `interval`. With fixed windows, the count resets at each window boundary, so tasks can burst there.
For example, with `intervalCap: 2` and `interval: 1000`: - __Fixed windows (default):__ 2 tasks can start at 999 ms and 2 more at 1000 ms, so 4 tasks start within 1 ms. - __Sliding window (strict):__ No more than 2 tasks start in any 1000 ms period.
Strict mode uses more resources, because it keeps the start time of each task. Use it when an API enforces strict rate limits.
`carryoverIntervalCount` has no effect in strict mode, because strict mode counts start times, not running tasks.
@default false */ readonly strict?: boolean | undefined;} & TimeoutOptions;type Queue
type Queue<Element, Options> = { size: number; filter: (options: Readonly<Partial<Options>>) => Element[]; dequeue: () => Element | undefined; enqueue: (run: Element, options?: Partial<Options>) => void; setPriority: (id: string, priority: number) => void; remove: (id: string) => void;};type QueueAddOptions
type QueueAddOptions = { /** Tasks with a higher priority start first. `Infinity` and `-Infinity` work. `.add()` rejects with a `TypeError` when it is `NaN` or not a number. The waiting tasks are kept sorted, so a task with a higher priority than the last waiting task takes time in proportion to the number of waiting tasks to add. For tens of thousands of waiting tasks with many different priorities, use a custom `queueClass`.
@default 0 */ readonly priority?: number | undefined; /** A unique identifier for the task, used to change its priority with `.setPriority()`. Defaults to an incrementing number as a string (`'1'`, `'2'`, and so on), so do not use such strings as your own ids. */ id?: string | undefined; /** Override the timeout of the queue for this task. `undefined` means no timeout.
@default The `timeout` of the queue */ timeout?: number | undefined;} & TaskOptions;type RunFunction
type RunFunction = () => Promise<unknown>;type TaskOptions
type TaskOptions = { /** An [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) to cancel the task. If it aborts while the task waits, the task is removed and `.add()` rejects with the [abort reason](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/reason). If it aborts while the task runs, `.add()` rejects and the concurrency slot is freed, but the task keeps running unless it handles the signal itself.
@example ``` import PQueue from 'p-queue'; import got, {CancelError} from 'got';
const queue = new PQueue();
const controller = new AbortController();
setTimeout(() => { controller.abort(); }, 100);
try { await queue.add(async ({signal}) => { const request = got('https://sindresorhus.com');
signal?.addEventListener('abort', () => { request.cancel(); });
try { return await request; } catch (error) { if (!(error instanceof CancelError)) { throw error; } } }, {signal: controller.signal}); } catch (error) { if (!(error instanceof DOMException)) { throw error; } } ``` */ readonly signal?: AbortSignal | undefined;};Package Files (4)
Dependencies (0)
No dependencies.
Dev Dependencies (11)
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/p-queue.
- Markdown[](https://www.jsdocs.io/package/p-queue)
- HTML<a href="https://www.jsdocs.io/package/p-queue"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 3027 ms. - Missing or incorrect documentation? Open an issue for this package.
