### NPM Installation Commands Source: https://github.com/jessetane/queue/blob/master/readme.md Provides the commands to install the 'queue' package using npm or yarn package managers. ```bash npm install queue yarn add queue ``` -------------------------------- ### Start Queue Processing with start() (JavaScript) Source: https://context7.com/jessetane/queue/llms.txt Explains how to initiate queue processing using the start() method. It can accept a callback for completion notification or return a Promise when called without arguments. ```javascript import Queue from 'queue' const q = new Queue({ results: [] }) q.push( cb => cb(null, 'task1'), cb => cb(null, 'task2') ) // Callback-based start q.start((err, results) => { if (err) throw err console.log('All done:', results) }) // Promise-based start (use separately, not after callback version) const q2 = new Queue({ results: [] }) q2.push(cb => cb(null, 'async result')) try { await q2.start() console.log('Completed:', q2.results) // [['async result']] } catch (err) { console.error('Queue failed:', err) } ``` -------------------------------- ### start() Source: https://context7.com/jessetane/queue/llms.txt Starts processing the queue. Accepts an optional callback or returns a Promise when called without arguments. ```APIDOC ## start() Starts processing the queue. Accepts an optional callback or returns a Promise when called without arguments. ### Method `queue.start(callback)` or `await queue.start()` ### Parameters - **callback** (function) - Optional. A callback function that is executed when all jobs in the queue have completed. It receives `(err, results)` as arguments. ### Request Example ```javascript import Queue from 'queue' const q = new Queue({ results: [] }) q.push( cb => cb(null, 'task1'), cb => cb(null, 'task2') ) // Callback-based start q.start((err, results) => { if (err) throw err console.log('All done:', results) }) // Promise-based start (use separately, not after callback version) const q2 = new Queue({ results: [] }) q2.push(cb => cb(null, 'async result')) try { await q2.start() console.log('Completed:', q2.results) // [['async result']] } catch (err) { console.error('Queue failed:', err) } ``` ``` -------------------------------- ### JavaScript Example: Using the Queue Class Source: https://github.com/jessetane/queue/blob/master/readme.md Demonstrates how to use the Queue class to manage asynchronous jobs. It shows adding jobs using array methods, handling callbacks and promises, setting timeouts, and listening to events like 'success' and 'timeout'. ```javascript import Queue from 'queue' const q = new Queue({ results: [] }) // add jobs using the familiar Array API q.push(cb => { const result = 'two' cb(null, result) }) q.push( cb => { const result = 'four' cb(null, result) }, cb => { const result = 'five' cb(null, result) } ) // jobs can accept a callback or return a promise q.push(() => { return new Promise((resolve, reject) => { const result = 'one' resolve(result) }) }) q.unshift(cb => { const result = 'one' cb(null, result) }) q.splice(2, 0, cb => { const result = 'three' cb(null, result) }) // use the timeout feature to deal with jobs that // take too long or forget to execute a callback q.timeout = 100 q.addEventListener('timeout', e => { console.log('job timed out:', e.detail.job.toString().replace(/\n/g, '')) e.detail.next() }) q.push(cb => { setTimeout(() => { console.log('slow job finished') cb() }, 200) }) q.push(cb => { console.log('forgot to execute callback') }) // jobs can also override the queue's timeout // on a per-job basis function extraSlowJob (cb) { setTimeout(() => { console.log('extra slow job finished') cb() }, 400) } extraSlowJob.timeout = 500 q.push(extraSlowJob) // jobs can also opt-out of the timeout altogether function superSlowJob (cb) { setTimeout(() => { console.log('super slow job finished') cb() }, 1000) } superSlowJob.timeout = null q.push(superSlowJob) // get notified when jobs complete q.addEventListener('success', e => { console.log('job finished processing:', e.detail.toString().replace(/\n/g, '')) console.log('The result is:', e.detail.result) }) // begin processing, get notified on end / failure q.start(err => { if (err) throw err console.log('all done:', q.results) }) ``` -------------------------------- ### Control Concurrent Job Execution with Concurrency in JavaScript Source: https://context7.com/jessetane/queue/llms.txt The concurrency option limits how many jobs run simultaneously. This value can be changed dynamically during execution, allowing for flexible resource management. The example demonstrates how jobs start and finish based on the concurrency limit. ```javascript import Queue from 'queue' const q = new Queue({ concurrency: 2 }) const running = [] const results = [] // These jobs track when they start/end const makeJob = (id, delay) => cb => { running.push(id) console.log(`Started: ${id}, Running: [${running}]`) setTimeout(() => { running.splice(running.indexOf(id), 1) results.push(id) cb() }, delay) } q.push( makeJob('A', 100), makeJob('B', 150), makeJob('C', 50), makeJob('D', 100) ) q.start(() => { console.log('Order completed:', results) }) // Output: // Started: A, Running: [A] // Started: B, Running: [A, B] (2 concurrent) // Started: C, Running: [B, C] (A finished, C starts) // Started: D, Running: [C, D] (B finished, D starts) // Order completed: ['A', 'C', 'B', 'D'] ``` -------------------------------- ### Add Jobs to Queue using push() (JavaScript) Source: https://context7.com/jessetane/queue/llms.txt Shows how to add single or multiple jobs to the end of the queue using the push() method. Supports callback-based, Promise-based, and async/await functions. Processing starts automatically if autostart is enabled. ```javascript import Queue from 'queue' const q = new Queue({ results: [] }) // Add single job with callback q.push(cb => { setTimeout(() => { cb(null, 'result1') }, 100) }) // Add multiple jobs at once q.push( cb => cb(null, 'result2'), cb => cb(null, 'result3') ) // Add Promise-based job q.push(() => { return new Promise(resolve => { resolve('result4') }) }) // Add async/await job q.push(async () => { const data = await fetch('https://api.example.com/data') return data.json() }) q.start(err => { if (err) throw err console.log(q.results) // [['result1'], ['result2'], ['result3'], ['result4'], [...]] }) ``` -------------------------------- ### Pause and Resume Queue with stop() and start() (JavaScript) Source: https://context7.com/jessetane/queue/llms.txt Demonstrates how to pause the queue after the current jobs complete using stop(), and then resume processing later with start(). This is useful for controlling task execution flow. ```javascript import Queue from 'queue' const q = new Queue({ concurrency: 1 }) let jobCount = 0 q.push( cb => { jobCount++; setTimeout(cb, 100) }, cb => { jobCount++; setTimeout(cb, 100) }, cb => { jobCount++; setTimeout(cb, 100) } ) q.start() // Stop after first job completes setTimeout(() => { q.stop() console.log('Stopped. Jobs completed:', jobCount) // 1 // Resume processing setTimeout(() => { q.start(() => { console.log('Resumed and finished. Total jobs:', jobCount) // 3 }) }, 500) }, 150) ``` -------------------------------- ### Implement Promise-Based Wrapper for Queue Concurrency Control in JavaScript Source: https://context7.com/jessetane/queue/llms.txt This JavaScript example shows a 'ConcurrencyQueue' class that wraps the standard Queue to provide Promise-based results, enabling seamless integration with async/await. It requires the 'queue' package and utilizes the Fetch API. ```javascript import Queue from 'queue' class ConcurrencyQueue { constructor(concurrency = 5) { this.queue = new Queue({ autostart: true, concurrency }) this.jobPromises = new Map() this.queue.addEventListener('success', e => { const { resolve } = this.jobPromises.get(e.detail.job) this.jobPromises.delete(e.detail.job) resolve(e.detail.result[0]) }) this.queue.addEventListener('error', e => { const { reject } = this.jobPromises.get(e.detail.job) this.jobPromises.delete(e.detail.job) reject(e.detail.error) }) } async add(asyncFn) { return new Promise((resolve, reject) => { const job = async () => asyncFn() this.jobPromises.set(job, { resolve, reject }) this.queue.push(job) }) } } // Usage const limiter = new ConcurrencyQueue(2) async function fetchWithLimit(urls) { const results = await Promise.all( urls.map(url => limiter.add(() => fetch(url).then(r => r.json()))) ) return results } // Only 2 requests run concurrently const data = await fetchWithLimit([ 'https://api.example.com/1', 'https://api.example.com/2', 'https://api.example.com/3', 'https://api.example.com/4' ]) ``` -------------------------------- ### Handle Queue Job Lifecycle Events in JavaScript Source: https://context7.com/jessetane/queue/llms.txt This snippet demonstrates how to use the Queue's event listeners to react to job lifecycle events such as start, success, error, timeout, and end. It requires the 'queue' package. ```javascript import Queue from 'queue' const q = new Queue({ timeout: 1000 }) // Fires before each job starts q.addEventListener('start', e => { console.log('Starting job:', e.detail.job.name || 'anonymous') }) // Fires when a job completes successfully q.addEventListener('success', e => { console.log('Job succeeded with result:', e.detail.result) }) // Fires when a job passes an error to callback q.addEventListener('error', e => { console.log('Job failed:', e.detail.error.message) console.log('Failed job:', e.detail.job) }) // Fires when a job exceeds timeout q.addEventListener('timeout', e => { console.log('Job timed out') e.detail.next() // Must call to continue queue }) // Fires when all jobs complete or on error q.addEventListener('end', e => { if (e.detail.error) { console.log('Queue ended with error:', e.detail.error) } else { console.log('Queue completed successfully') } }) q.push( function successJob(cb) { cb(null, 'ok') }, function errorJob(cb) { cb(new Error('failed')) } ) q.start() ``` -------------------------------- ### stop() Source: https://context7.com/jessetane/queue/llms.txt Pauses the queue after the current jobs complete. Processing can be resumed with start(). ```APIDOC ## stop() Pauses the queue after the current jobs complete. Processing can be resumed with start(). ### Method `queue.stop()` ### Request Example ```javascript import Queue from 'queue' const q = new Queue({ concurrency: 1 }) let jobCount = 0 q.push( cb => { jobCount++; setTimeout(cb, 100) }, cb => { jobCount++; setTimeout(cb, 100) }, cb => { jobCount++; setTimeout(cb, 100) } ) q.start() // Stop after first job completes setTimeout(() => { q.stop() console.log('Stopped. Jobs completed:', jobCount) // 1 // Resume processing setTimeout(() => { q.start(() => { console.log('Resumed and finished. Total jobs:', jobCount) // 3 }) }, 500) }, 150) ``` ``` -------------------------------- ### NPM Test Commands Source: https://github.com/jessetane/queue/blob/master/readme.md Lists the commands for running tests and development builds for the 'queue' package. ```bash npm test npm run dev // for testing in a browser, open test directory (and your console) ``` -------------------------------- ### Create Queue Instance with Configuration (JavaScript) Source: https://context7.com/jessetane/queue/llms.txt Demonstrates how to create a new Queue instance with various configuration options such as concurrency, timeout, autostart, and result collection. Defaults can be used by omitting options. ```javascript import Queue from 'queue' // Create queue with all options const q = new Queue({ concurrency: 2, // Max 2 jobs running at once (default: Infinity) timeout: 5000, // 5 second timeout per job (default: 0 = no timeout) autostart: false, // Don't start automatically (default: false) results: [] // Collect job results in this array (default: null) }) // Create queue with defaults const defaultQueue = new Queue() ``` -------------------------------- ### Queue Constructor Source: https://context7.com/jessetane/queue/llms.txt Creates a new Queue instance with optional configuration for concurrency, timeout, autostart, and result collection. ```APIDOC ## Constructor Creates a new Queue instance with optional configuration for concurrency, timeout, autostart, and result collection. ### Method `new Queue(options)` ### Parameters #### Options Object - **concurrency** (number) - Optional - Maximum number of jobs to run concurrently. Defaults to `Infinity`. - **timeout** (number) - Optional - Timeout in milliseconds for each job. Defaults to `0` (no timeout). - **autostart** (boolean) - Optional - Whether to start processing jobs automatically. Defaults to `false`. - **results** (array) - Optional - An array to collect job results. Defaults to `null`. ### Request Example ```javascript import Queue from 'queue' // Create queue with all options const q = new Queue({ concurrency: 2, timeout: 5000, autostart: false, results: [] }) // Create queue with defaults const defaultQueue = new Queue() ``` ``` -------------------------------- ### Manage Queue Jobs Using Array Methods in JavaScript Source: https://context7.com/jessetane/queue/llms.txt This code illustrates how to use standard Array methods like pop, shift, indexOf, and reverse to manage jobs within a Queue instance. It requires the 'queue' package. ```javascript import Queue from 'queue' const q = new Queue() const job1 = cb => cb(null, 'one') const job2 = cb => cb(null, 'two') const job3 = cb => cb(null, 'three') q.push(job1, job2, job3) // Find job index console.log(q.indexOf(job2)) // 1 // Remove last job const removed = q.pop() // job3 removed // Remove first job const first = q.shift() // job1 removed // Reverse job order q.push(job1, job3) q.reverse() // Order: job3, job2, job1 // Get queue length (pending + jobs) console.log(q.length) // 3 ``` -------------------------------- ### Enable Autostart Mode for Automatic Job Processing in JavaScript Source: https://context7.com/jessetane/queue/llms.txt Autostart mode automatically begins processing jobs as they are added to the queue. If the queue becomes empty, it will automatically restart when new jobs are pushed. Event listeners for 'end' and 'success' can provide feedback on queue status. ```javascript import Queue from 'queue' const q = new Queue({ autostart: true, concurrency: 1 }) q.addEventListener('end', () => { console.log('Queue empty, waiting for more jobs...') }) q.addEventListener('success', e => { console.log('Completed:', e.detail.result) }) // Jobs start immediately when pushed q.push(cb => { setTimeout(() => cb(null, 'first'), 100) }) q.push(cb => { setTimeout(() => cb(null, 'second'), 100) }) // Add more jobs later - they auto-process setTimeout(() => { q.push(cb => { setTimeout(() => cb(null, 'third'), 100) }) }, 500) // Output: // Completed: ['first'] // Completed: ['second'] // Queue empty, waiting for more jobs... // Completed: ['third'] // Queue empty, waiting for more jobs... ``` -------------------------------- ### push() Source: https://context7.com/jessetane/queue/llms.txt Adds one or more jobs to the end of the queue. Returns the new length of the queue. If autostart is enabled, processing begins immediately. ```APIDOC ## push() Adds one or more jobs to the end of the queue. Returns the new length of the queue. If autostart is enabled, processing begins immediately. ### Method `queue.push(job1, job2, ...)` ### Parameters - **job** (function) - A job function that accepts a callback or returns a Promise. It can be a callback-based function `(cb) => { ... cb(err, result) ... }` or a Promise-based function `() => Promise.resolve(result)` or an `async` function. ### Request Example ```javascript import Queue from 'queue' const q = new Queue({ results: [] }) // Add single job with callback q.push(cb => { setTimeout(() => { cb(null, 'result1') }, 100) }) // Add multiple jobs at once q.push( cb => cb(null, 'result2'), cb => cb(null, 'result3') ) // Add Promise-based job q.push(() => { return new Promise(resolve => { resolve('result4') }) }) // Add async/await job q.push(async () => { const data = await fetch('https://api.example.com/data') return data.json() }) q.start(err => { if (err) throw err console.log(q.results) // [['result1'], ['result2'], ['result3'], ['result4'], [...]] }) ``` ``` -------------------------------- ### Add High-Priority Jobs with unshift() (JavaScript) Source: https://context7.com/jessetane/queue/llms.txt Illustrates adding jobs to the front of the queue using the unshift() method, ensuring they are processed before existing jobs. This is useful for implementing priority queues. ```javascript import Queue from 'queue' const q = new Queue({ concurrency: 1, results: [] }) q.push(cb => { cb(null, 'added first, runs second') }) // Add high-priority job to front q.unshift(cb => { cb(null, 'added second, runs first') }) q.start(err => { console.log(q.results) // [['added second, runs first'], ['added first, runs second']] }) ``` -------------------------------- ### unshift() Source: https://context7.com/jessetane/queue/llms.txt Adds one or more jobs to the front of the queue, giving them priority over existing jobs. ```APIDOC ## unshift() Adds one or more jobs to the front of the queue, giving them priority over existing jobs. ### Method `queue.unshift(job1, job2, ...)` ### Parameters - **job** (function) - A job function that accepts a callback or returns a Promise. It can be a callback-based function `(cb) => { ... cb(err, result) ... }` or a Promise-based function `() => Promise.resolve(result)` or an `async` function. ### Request Example ```javascript import Queue from 'queue' const q = new Queue({ concurrency: 1, results: [] }) q.push(cb => { cb(null, 'added first, runs second') }) // Add high-priority job to front q.unshift(cb => { cb(null, 'added second, runs first') }) q.start(err => { console.log(q.results) // [['added second, runs first'], ['added first, runs second']] }) ``` ``` -------------------------------- ### Manipulate Queue with splice() (JavaScript) Source: https://context7.com/jessetane/queue/llms.txt Demonstrates using the splice() method to add and/or remove jobs at a specific position within the queue. This allows for dynamic modification of the job sequence. ```javascript import Queue from 'queue' const q = new Queue({ concurrency: 1, results: [] }) q.push( cb => cb(null, 'one'), cb => cb(null, 'four') ) // Insert 'two' and 'three' at index 1, removing 0 elements q.splice(1, 0, cb => cb(null, 'two'), cb => cb(null, 'three') ) q.start(err => { console.log(q.results) // [['one'], ['two'], ['three'], ['four']] }) ``` -------------------------------- ### TypeScript: Wrapper Class for Queue with Promise API Source: https://github.com/jessetane/queue/wiki/Recipes Defines a TypeScript class 'MyJobQueue' that wraps a queue instance. It allows adding jobs and returns a Promise that resolves or rejects based on the job's completion or failure. This class manages job-specific resolve/reject functions using a Map. ```typescript class MyJobQueue { private theQueue; private jobResolveRejectMap = new Map(); constructor() { this.theQueue = queue(/* Your options */); this.theQueue.on('success', this.onJobComplete.bind(this)); this.theQueue.on('error', this.onJobFailed.bind(this)); } async addJob(job): Promise { this.theQueue.push(job); return new Promise((resolve, reject) => { this.jobResolveRejectMap.set(job, { resolve, reject }); }); } onJobComplete(result, job) { const { resolve } = this.jobResolveRejectMap.get(job); this.jobResolveRejectMap.delete(job); resolve(result); } onJobFailed(error, job) { const { reject } = this.jobResolveRejectMap.get(job); this.jobResolveRejectMap.delete(job); reject(error); } } ``` ```typescript // You'll probably need just a single instance const myQueue: MyJobQueue = new MyJobQueue(); const result = await myQueue.addJob(() => { return new Promise(resolve => { setTimeout(() => resolve(42), 100); }); }) // result === 42 ``` -------------------------------- ### Collect Job Return Values with Results Option in JavaScript Source: https://context7.com/jessetane/queue/llms.txt The results option collects return values from all jobs into an array, preserving the order of execution. This allows you to easily access the output of each job after the queue has finished processing. The results array can be initialized with custom values. ```javascript import Queue from 'queue' const q = new Queue({ results: [] }) q.push( cb => cb(null, 42), cb => cb(null, 'hello', 'world'), cb => { setTimeout(() => cb(null, { data: 'async result' }), 100) }, async () => { return 'promise result' } ) q.start((err, results) => { console.log(results) // [ // [42], // ['hello', 'world'], // [{ data: 'async result' }], // ['promise result'] // ] }) ``` -------------------------------- ### Configure Job Timeouts Globally and Per-Job in JavaScript Source: https://context7.com/jessetane/queue/llms.txt The timeout option sets a global timeout for jobs. Individual jobs can override this with a custom timeout value or opt out entirely by setting their timeout property to null. A 'timeout' event listener can handle timeout occurrences. ```javascript import Queue from 'queue' const q = new Queue({ timeout: 100 }) q.addEventListener('timeout', e => { console.log('Job timed out:', e.detail.job.name || 'anonymous') e.detail.next() // Continue to next job }) // This job will timeout (takes 200ms, limit is 100ms) q.push(function slowJob(cb) { setTimeout(cb, 200) }) // This job overrides timeout to 500ms function customTimeoutJob(cb) { setTimeout(() => { console.log('Custom timeout job completed') cb() }, 300) } customTimeoutJob.timeout = 500 q.push(customTimeoutJob) // This job opts out of timeout entirely function noTimeoutJob(cb) { setTimeout(() => { console.log('No timeout job completed') cb() }, 1000) } noTimeoutJob.timeout = null q.push(noTimeoutJob) q.start(() => { console.log('All done') }) // Output: // Job timed out: slowJob // Custom timeout job completed // No timeout job completed // All done ``` -------------------------------- ### splice() Source: https://context7.com/jessetane/queue/llms.txt Adds and/or removes jobs at a specific position in the queue. ```APIDOC ## splice() Adds and/or removes jobs at a specific position in the queue. ### Method `queue.splice(index, deleteCount, job1, job2, ...)` ### Parameters - **index** (number) - The index at which to start changing the queue. - **deleteCount** (number) - The number of jobs to remove from the queue starting at `index`. - **job** (function) - One or more job functions to add to the queue, beginning at `index`. ### Request Example ```javascript import Queue from 'queue' const q = new Queue({ concurrency: 1, results: [] }) q.push( cb => cb(null, 'one'), cb => cb(null, 'four') ) // Insert 'two' and 'three' at index 1, removing 0 elements q.splice(1, 0, cb => cb(null, 'two'), cb => cb(null, 'three') ) q.start(err => { console.log(q.results) // [['one'], ['two'], ['three'], ['four']] }) ``` ``` -------------------------------- ### Stop Queue Immediately with end() in JavaScript Source: https://context7.com/jessetane/queue/llms.txt The end() method immediately stops the queue and removes all pending jobs. It can optionally take an error object to indicate the reason for stopping. This is useful for emergency stops or cancellations. ```javascript import Queue from 'queue' const q = new Queue({ concurrency: 1 }) q.push( cb => setTimeout(() => { console.log('job 1'); cb() }, 100), cb => setTimeout(() => { console.log('job 2'); cb() }, 100), cb => setTimeout(() => { console.log('job 3'); cb() }, 100) ) q.addEventListener('end', e => { if (e.detail.error) { console.log('Queue ended with error:', e.detail.error.message) } }) q.start() // Emergency stop - clears all pending jobs setTimeout(() => { q.end(new Error('cancelled by user')) // Output: 'job 1', then 'Queue ended with error: cancelled by user' // Jobs 2 and 3 are discarded }, 150) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.