'use strict'const queue = require('fastq')(worker, 1)queue.push(42, function (err, result) { if (err) { throw err } console.log('the result is', result)})function worker (arg, cb) { cb(null, arg * 2)}
Usage (promise API)
const queue = require('fastq').promise(worker, 1)async function worker (arg) { return arg * 2}async function run () { const result = await queue.push(42) console.log('the result is', result)}run()
Setting "this"
'use strict'const that = { hello: 'world' }const queue = require('fastq')(that, worker, 1)queue.push(42, function (err, result) { if (err) { throw err } console.log(this) console.log('the result is', result)})function worker (arg, cb) { console.log(this) cb(null, arg * 2)}
Using with TypeScript (callback API)
'use strict'import * as fastq from "fastq";import type { queue, done } from "fastq";type Task = { id: number}const q: queue<Task> = fastq(worker, 1)q.push({ id: 42})function worker (arg: Task, cb: done) { console.log(arg.id) cb(null)}
Using with TypeScript (promise API)
'use strict'import * as fastq from "fastq";import type { queueAsPromised } from "fastq";type Task = { id: number}const q: queueAsPromised<Task> = fastq.promise(asyncWorker, 1)q.push({ id: 42}).catch((err) => console.error(err))async function asyncWorker (arg: Task): Promise<void> { // No need for a try-catch block, fastq handles errors automatically console.log(arg.id)}
Creates a new queue with Promise apis. It also offers all the methods
and properties of the object returned by fastqueue with the modified
push and unshift methods.
Node v10+ is required to use the promisified version.
Arguments:
that, optional context of the worker function.
worker, worker function, it would be called with that as this,
if that is specified. It MUST return a Promise.
concurrency, number of concurrent tasks that could be executed in
parallel.
queue.push(task) => Promise
Add a task at the end of the queue. The returned Promise will be fulfilled (rejected)
when the task is completed successfully (unsuccessfully).
This promise could be ignored as it will not lead to a 'unhandledRejection'.
queue.unshift(task) => Promise
Add a task at the beginning of the queue. The returned Promise will be fulfilled (rejected)
when the task is completed successfully (unsuccessfully).
This promise could be ignored as it will not lead to a 'unhandledRejection'.
queue.drained() => Promise
Wait for the queue to be drained. The returned Promise will be resolved when all tasks in the queue have been processed by a worker.
This promise could be ignored as it will not lead to a 'unhandledRejection'.