Gathering detailed insights and metrics for p-queue-compat
Gathering detailed insights and metrics for p-queue-compat
Gathering detailed insights and metrics for p-queue-compat
Gathering detailed insights and metrics for p-queue-compat
npm install p-queue-compat
Typescript
Module System
Min. Node Version
Node Version
NPM Version
95.7
Supply Chain
100
Quality
78
Maintenance
100
Vulnerability
100
License
JavaScript (100%)
Total Downloads
958,252
Last Day
805
Last Week
19,270
Last Month
68,469
Last Year
518,190
2 Stars
888 Commits
2 Watching
2 Branches
2 Contributors
Minified
Minified + Gzipped
Latest Version
1.0.227
Package Id
p-queue-compat@1.0.227
Unpacked Size
60.91 kB
Size
11.73 kB
File Count
18
NPM Version
10.8.2
Node Version
20.17.0
Publised On
18 Oct 2024
Cumulative downloads
Total Downloads
Last day
-31%
805
Compared to previous day
Last week
11.2%
19,270
Compared to previous week
Last month
-4.4%
68,469
Compared to previous month
Last year
457%
518,190
Compared to previous year
2
23
Compatible version of p-queue. Exports cjs and mjs versions of p-queue and lets node select the appropriate one. Please see original readme below for details.
npm i --save p-queue-compat
1import PQueue from 'p-queue-compat'; 2import got from 'got'; 3 4const queue = new PQueue({concurrency: 1}); 5 6(async () => { 7 await queue.add(() => got('https://sindresorhus.com')); 8 console.log('Done: sindresorhus.com'); 9})();
Promise queue with concurrency control
Useful for rate-limiting async (or sync) operations. For example, when interacting with a REST API or when doing CPU/memory intensive tasks.
For servers, you probably want a Redis-backed job queue instead.
Note that the project is feature complete. We are happy to review pull requests, but we don't plan any further development. We are also not answering email support questions.
1npm install p-queue
Warning: This package is native ESM and no longer provides a CommonJS export. If your project uses CommonJS, you'll have to convert to ESM. Please don't open issues for questions regarding CommonJS / ESM.
Here we run only one promise at the time. For example, set concurrency
to 4 to run four promises at the same time.
1import PQueue from 'p-queue'; 2import got from 'got'; 3 4const queue = new PQueue({concurrency: 1}); 5 6(async () => { 7 await queue.add(() => got('https://sindresorhus.com')); 8 console.log('Done: sindresorhus.com'); 9})(); 10 11(async () => { 12 await queue.add(() => got('https://avajs.dev')); 13 console.log('Done: avajs.dev'); 14})(); 15 16(async () => { 17 const task = await getUnicornTask(); 18 await queue.add(task); 19 console.log('Done: Unicorn task'); 20})();
Returns a new queue
instance, which is an EventEmitter3
subclass.
Type: object
Type: number
Default: Infinity
Minimum: 1
Concurrency limit.
Type: number
Per-operation timeout in milliseconds. Operations fulfill once timeout
elapses if they haven't already.
Type: boolean
Default: false
Whether or not a timeout is considered an exception.
Type: boolean
Default: true
Whether queue tasks within concurrency limit, are auto-executed as soon as they're added.
Type: Function
Class with a enqueue
and dequeue
method, and a size
getter. See the Custom QueueClass section.
Type: number
Default: Infinity
Minimum: 1
The max number of runs in the given interval of time.
Type: number
Default: 0
Minimum: 0
The length of time in milliseconds before the interval count resets. Must be finite.
Type: boolean
Default: false
If true
, specifies that any pending Promises, should be carried over into the next interval and counted against the intervalCap
. If false
, any of those pending Promises will not count towards the next intervalCap
.
PQueue
instance.
Adds a sync or async task to the queue. Always returns a promise.
Note: If your items can potentially throw an exception, you must handle those errors from the returned Promise or they may be reported as an unhandled Promise rejection and potentially cause your process to exit immediately.
Type: Function
Promise-returning/async function. When executed, it will receive {signal}
as the first argument.
Type: object
Type: number
Default: 0
Priority of operation. Operations with greater priority will be scheduled first.
AbortSignal
for cancellation of the operation. When aborted, it will be removed from the queue and the queue.add()
call will reject with an error. If the operation is already running, the signal will need to be handled by the operation itself.
1import PQueue from 'p-queue'; 2import got, {CancelError} from 'got'; 3 4const queue = new PQueue(); 5 6const controller = new AbortController(); 7 8try { 9 await queue.add(({signal}) => { 10 const request = got('https://sindresorhus.com'); 11 12 signal.addEventListener('abort', () => { 13 request.cancel(); 14 }); 15 16 try { 17 return await request; 18 } catch (error) { 19 if (!(error instanceof CancelError)) { 20 throw error; 21 } 22 } 23 }, {signal: controller.signal}); 24} catch (error) { 25 if (!(error instanceof DOMException)) { 26 throw error; 27 } 28}
Same as .add()
, but accepts an array of sync or async functions and returns a promise that resolves when all functions are resolved.
Put queue execution on hold.
Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via options.autoStart = false
or by .pause()
method.)
Returns this
(the instance).
Returns a promise that settles when the queue becomes empty.
Can be called multiple times. Useful if you for example add additional items at a later time.
Returns a promise that settles when the queue becomes empty, and all promises have completed; queue.size === 0 && queue.pending === 0
.
The difference with .onEmpty
is that .onIdle
guarantees that all work from the queue has finished. .onEmpty
merely signals that the queue is empty, but it could mean that some promises haven't completed yet.
Returns a promise that settles when the queue size is less than the given limit: queue.size < limit
.
If you want to avoid having the queue grow beyond a certain size you can await queue.onSizeLessThan()
before adding a new item.
Note that this only limits the number of items waiting to start. There could still be up to concurrency
jobs already running that this call does not include in its calculation.
Clear the queue.
Size of the queue, the number of queued items waiting to run.
Size of the queue, filtered by the given options.
For example, this can be used to find the number of items remaining in the queue with a specific priority level.
1import PQueue from 'p-queue'; 2 3const queue = new PQueue(); 4 5queue.add(async () => 'š¦', {priority: 1}); 6queue.add(async () => 'š¦', {priority: 0}); 7queue.add(async () => 'š¦', {priority: 1}); 8 9console.log(queue.sizeBy({priority: 1})); 10//=> 2 11 12console.log(queue.sizeBy({priority: 0})); 13//=> 1
Number of running items (no longer in the queue).
Whether the queue is currently paused.
Emitted as each item is processed in the queue for the purpose of tracking progress.
1import delay from 'delay'; 2import PQueue from 'p-queue'; 3 4const queue = new PQueue({concurrency: 2}); 5 6let count = 0; 7queue.on('active', () => { 8 console.log(`Working on item #${++count}. Size: ${queue.size} Pending: ${queue.pending}`); 9}); 10 11queue.add(() => Promise.resolve()); 12queue.add(() => delay(2000)); 13queue.add(() => Promise.resolve()); 14queue.add(() => Promise.resolve()); 15queue.add(() => delay(500));
Emitted when an item completes without error.
1import delay from 'delay'; 2import PQueue from 'p-queue'; 3 4const queue = new PQueue({concurrency: 2}); 5 6queue.on('completed', result => { 7 console.log(result); 8}); 9 10queue.add(() => Promise.resolve('hello, world!'));
Emitted if an item throws an error.
1import delay from 'delay'; 2import PQueue from 'p-queue'; 3 4const queue = new PQueue({concurrency: 2}); 5 6queue.on('error', error => { 7 console.error(error); 8}); 9 10queue.add(() => Promise.reject(new Error('error')));
Emitted every time the queue becomes empty.
Useful if you for example add additional items at a later time.
Emitted every time the queue becomes empty and all promises have completed; queue.size === 0 && queue.pending === 0
.
The difference with empty
is that idle
guarantees that all work from the queue has finished. empty
merely signals that the queue is empty, but it could mean that some promises haven't completed yet.
1import delay from 'delay'; 2import PQueue from 'p-queue'; 3 4const queue = new PQueue(); 5 6queue.on('idle', () => { 7 console.log(`Queue is idle. Size: ${queue.size} Pending: ${queue.pending}`); 8}); 9 10const job1 = queue.add(() => delay(2000)); 11const job2 = queue.add(() => delay(500)); 12 13await job1; 14await job2; 15// => 'Queue is idle. Size: 0 Pending: 0' 16 17await queue.add(() => delay(600)); 18// => 'Queue is idle. Size: 0 Pending: 0'
The idle
event is emitted every time the queue reaches an idle state. On the other hand, the promise the onIdle()
function returns resolves once the queue becomes idle instead of every time the queue is idle.
Emitted every time the add method is called and the number of pending or queued tasks is increased.
Emitted every time a task is completed and the number of pending or queued tasks is decreased. This is emitted regardless of whether the task completed normally or with an error.
1import delay from 'delay'; 2import PQueue from 'p-queue'; 3 4const queue = new PQueue(); 5 6queue.on('add', () => { 7 console.log(`Task is added. Size: ${queue.size} Pending: ${queue.pending}`); 8}); 9 10queue.on('next', () => { 11 console.log(`Task is completed. Size: ${queue.size} Pending: ${queue.pending}`); 12}); 13 14const job1 = queue.add(() => delay(2000)); 15const job2 = queue.add(() => delay(500)); 16 17await job1; 18await job2; 19//=> 'Task is added. Size: 0 Pending: 1' 20//=> 'Task is added. Size: 0 Pending: 2' 21 22await queue.add(() => delay(600)); 23//=> 'Task is completed. Size: 0 Pending: 1' 24//=> 'Task is completed. Size: 0 Pending: 0'
A more advanced example to help you understand the flow.
1import delay from 'delay'; 2import PQueue from 'p-queue'; 3 4const queue = new PQueue({concurrency: 1}); 5 6(async () => { 7 await delay(200); 8 9 console.log(`8. Pending promises: ${queue.pending}`); 10 //=> '8. Pending promises: 0' 11 12 (async () => { 13 await queue.add(async () => 'š'); 14 console.log('11. Resolved') 15 })(); 16 17 console.log('9. Added š'); 18 19 console.log(`10. Pending promises: ${queue.pending}`); 20 //=> '10. Pending promises: 1' 21 22 await queue.onIdle(); 23 console.log('12. All work is done'); 24})(); 25 26(async () => { 27 await queue.add(async () => 'š¦'); 28 console.log('5. Resolved') 29})(); 30console.log('1. Added š¦'); 31 32(async () => { 33 await queue.add(async () => 'š“'); 34 console.log('6. Resolved') 35})(); 36console.log('2. Added š“'); 37 38(async () => { 39 await queue.onEmpty(); 40 console.log('7. Queue is empty'); 41})(); 42 43console.log(`3. Queue size: ${queue.size}`); 44//=> '3. Queue size: 1` 45 46console.log(`4. Pending promises: ${queue.pending}`); 47//=> '4. Pending promises: 1'
$ node example.js
1. Added š¦
2. Added š“
3. Queue size: 1
4. Pending promises: 1
5. Resolved š¦
6. Resolved š“
7. Queue is empty
8. Pending promises: 0
9. Added š
10. Pending promises: 1
11. Resolved š
12. All work is done
For implementing more complex scheduling policies, you can provide a QueueClass in the options:
1import PQueue from 'p-queue'; 2 3class QueueClass { 4 constructor() { 5 this._queue = []; 6 } 7 8 enqueue(run, options) { 9 this._queue.push(run); 10 } 11 12 dequeue() { 13 return this._queue.shift(); 14 } 15 16 get size() { 17 return this._queue.length; 18 } 19 20 filter(options) { 21 return this._queue; 22 } 23} 24 25const queue = new PQueue({queueClass: QueueClass});
p-queue
will call corresponding methods to put and get operations from this queue.
concurrency
and intervalCap
options affect each other?They are just different constraints. The concurrency
option limits how many things run at the same time. The intervalCap
option limits how many things run in total during the interval (over time).
No vulnerabilities found.
Reason
23 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 10
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
Reason
Found 0/1 approved changesets -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
12 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-12-16
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More