npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ts-async-queue

v1.1.0

Published

A simple async-await task queue written in TypeScript

Downloads

650

Readme

ts-async-queue

Build Status Coverage status npm npm bundle size (minified) dependencies (minified)

A simple async-await task queue written in TypeScript

npm i -S ts-async-queue

What is it?

This is just a simple library for fail-safe async task execution, written in TypeScript. It utilizes OOP principles and TypeScript for painless management of complex task queues and easy extendability.

Unlike many similar libraries for working with async queues, this one behaves more like a "task-player" with start, pause, resume and stop functions. If you need execution concurrency or complex priority management - look elsewhere. Here you can simply enqueue, dequeue, start, stop, pause and resume in just 2KB of minified code. So if you need simplicity and small package - this is your choice.

Installation options

ts-async-queue comes with a couple of installation options:

format-name | exports | description ------------|------------|------------------- es5 | named | Contains an es5-compatible version of ts-async-queue es | named | ES6+-compatible version esnext | named | ES7+ version with non-transpiled async-awaits iife | tsQueue object | Creates a global variable tsQueue containing the exports. window-only. umd | tsQueue object | Same as iife, but also works for node.

The dist folder contains multiple files with names in a following format: /dist/ts-async-queue.{format-name}.js, where {format-name} is a format name from the table.

Named imports

// ES5/CommonJS
const { TaskQueue, QueueError } = require('ts-async-queue');

// If the first one does not work in your environment:
const { TaskQueue, QueueError } = require('ts-async-queue/dist/ts-async-queue.es5');

// ES6+/TypeScript
import { TaskQueue, QueueError } from 'ts-async-queue';
import { TaskQueue, QueueError } from 'ts-async-queue/dist/ts-async-queue.es'; // ES6-only
import { TaskQueue, QueueError } from 'ts-async-queue/dist/ts-async-queue.esnext'; // ES7+ only

Script imports

<!-- IIFE -->
<script src="https://unpkg.com/ts-async-queue"></script>

<!-- For specific versions of the library -->
<script src="https://unpkg.com/ts-async-queue/dist/ts-async-queue.{export-version}.js"></script>

Library exports

ts-async-queue has 2 named exports: TaskQueue and QueueError:

const { TaskQueue, QueueError } = require('ts-async-queue');
import { TaskQueue, QueueError } from 'ts-async-queue';

TaskQueue

Manages a queue of async tasks

See type declaration for more details

Initilize queue and manage tasks:

// Task is a simple function that recieves 0 arguments and returns a promise:
const task1 = () => Promise.resolve('task1');
const task2 = () => Promise.resolve('task2');
const task3 = () => Promise.resolve('task3');

// Initialize an empty task queue:
const queue = new TaskQueue();

// and enqueue tasks of your choice (one or more):
queue.enqueue(task1, task2, task3); // -> queue contains [task1, task2, task3]

// or dequeue them

// by index
queue.dequeue(1); // -> returns task2; queue contains [task1, task3]

// by task reference
queue.dequeue(task1); // -> returns task1; queue contains [task3]

// or simply pop the last one
queue.dequeue(); // dequeues the last task in; queue is empty now.
queue.pop(); // same as previous

// Or initialize a task queue with default tasks:
const queueWithElements = new TaskQueue([
  task1,
  task2,
  task3
]);

// Clear all tasks at once
queueWithElements.clear(); // -> queue is empty now ([]).

queue.start()

Starts task queue execution. Returns currenlty executed queue if execution already started.

const queue = new TaskQueue([
  task1,
  task2,
  task3
]);


/** Start the queue with
 * TaskQueue.start():
 */

// You can start a queue by calling the `start` function that returns a promise:
const endOfQueueExecution = queue.start();

// endOfQueueExecution is resolved as soon as the queue has finished executing all tasks,
// it always resolves to the array of task results in order of their execution:
endOfQueueExecution.then(results => {
  // If you only need only the last result, just do
  const result = results[results.length - 1];

  console.log(result); // -> task3
  console.log(results); // -> ['task1', 'task2', 'task3']
});

// If you don't care about results, you can also simply await the `start()`:
await queue.start(); // does the exact same procedure as the previous time
// .. do here whatever you want to do after the tasks stop executing

// If one execution is not enough, you can always restart:
queue.start();

queue.stop()

Stops queue execution and clears results.

/** Stop the queue with
 * TaskQueue.stop():
 */

// You can stop the queue execution at any task:
const stopped = queue.stop();

// The `stopped` promise resolves as soon as the queue stops executing:
stopped.then(results => {
  // Here, `results` contains the results of whatever tasks managed to finish their execution

  // If we try to stop the queue again, it will return the same result:
  queue.stop()
    .then(res => console.log(res)); // `res` is equal to `results`
});

queue.pause()

Pauses the queue's execution flow after a nearest task is completed. Returns a promise that resolves as soon as the queue is paused

queue.start();

/** Pause the queue with
 * TaskQueue.pause():
 */

// Pause resolves to results of tasks executed before the execution has been paused
const results = await queue.pause()
const amountOfTasksExecuted = results.length;

queue.resume()

Resumes a previously paused queue. Returns a promise that resolves as soon as the queue is completed

/** Resume the queue with
 * TaskQueue.resume():
 */

const results = await queue.resume();

console.log(results); // -> ['task1', 'task2', 'task3']

Instance properties

name | type | description -----|------|-------------------------------------- isRunning | boolean | true if the queue is currently executing length | number | Amount of tasks in the queue last | Task | The last task added to the queue peek() | Task | A method alias for last lastResults | Array | An array of results captured from the last queue execution currentTaskIndex | number | A task index at which the queue is currently running currentRunningTask | Task | A task which is currently running in the queue

QueueError

A simple error class that is raised if the queue encountered an error in a currently running task

Properties:

name | type | description -----|------|----------------------- message | string | An error message text queue | TaskQueue | The queue instance error is raised from data | any | Internal error data stack | string | Error stack trace failedTask | Task | The task at which the queue has failed failedTaskIndex | number | An index of the task at which the queue has failed

Usage example

const queue1 = new TaskQueue([
  () => Promise.resolve('task1'),
  () => Promise.resolve('task2')
]);

const queue2 = new TaskQueue([
  () => Promise.reject('task1') // This one rejects the promise, causing an exception to be thrown,
  () => Promise.resolve('task2')
]);

try {
  await queue1.start();
  await queue2.start();
} catch (e) {
  console.log(e.queue === queue2); // -> true

  console.log(e); // -> Queue paused at task #1 due to error in handler () => Promise.reject('task1')
}