Installation
$ npm install queue-promise
Usage
import Queue from "queue-promise";
const queue = new Queue({
concurrent: 1,
interval: 2000,
start: true
});
queue.on("start", () => );
queue.on("stop", () => );
queue.on("end", () => );
queue.on("resolve", data => console.log(data));
queue.on("reject", error => console.error(error));
queue.enqueue(asyncTaskA);
queue.enqueue(asyncTaskB);
queue.enqueue(asyncTaskC);
queue.enqueue(asyncTaskD);
API
new Queue(options)
Create a new Queue
instance.
Option | Default | Description |
---|
concurrent | 5 | How many tasks should be executed in parallel |
interval | 500 | How often should new tasks be executed (in ms) |
start | true | Whether it should automatically resolve new tasks as soon as they are added |
public .enqueue(tasks)
/.add(tasks)
Adds a new task to the queue. A task should be an async function (ES2017) or return a Promise. Throws an error if the provided task
is not a valid function.
Example:
async function getRepos(user) {
return await github.getRepos(user);
}
queue.enqueue(getRepos("userA"));
queue.enqueue(getRepos("userB"));
queue.enqueue([getRepos("userA"), getRepos("userB")]);
public .dequeue()
Manually resolves n concurrent (based od options.concurrent
) promises from the queue. Uses global Promises. Is called automatically if options.start
is set to true
. Emits resolve
and reject
events.
Example:
queue.enqueue(getRepos("userA"));
queue.enqueue(getRepos("userB"));
const userA = await queue.dequeue();
const userB = await queue.dequeue();
const [userA, userB] = await queue.dequeue();
public .on(event, callback)
Sets a callback
for an event
. You can set callback for those events: start
, stop
, resolve
, reject
, end
.
Example:
queue.on("resolve", data => …);
queue.on("reject", error => …);
queue.on("start", () => …);
queue.on("stop", () => …);
queue.on("end", () => …);
public .start()
Starts the queue – it will automatically dequeue tasks periodically. Emits start
event.
queue.enqueue(getRepos("userA"));
queue.enqueue(getRepos("userB"));
queue.enqueue(getRepos("userC"));
queue.enqueue(getRepos("userD"));
queue.start();
queue.on("resolve", data => …);
queue.on("reject", error => …);
public .stop()
Forces the queue to stop. New tasks will not be resolved automatically even if options.start
was set to true
. Emits stop
event.
public .clear()
Removes all tasks from the queue.
public .started
Whether the queue has been started or not.
public .stopped
Whether the queue has been forced to stop.
public .isEmpty
Whether the queue is empty, i.e. there's no tasks.
Tests
$ npm test