Promise-Queue

2.1.1 · active · verified Tue Apr 21

sb-promise-queue is a lightweight JavaScript/TypeScript utility library designed to manage and control the concurrency of asynchronous operations using a promise-based queue. Its current stable version is 2.1.1. It allows developers to specify a maximum number of promises that can run simultaneously, preventing resource exhaustion or rate-limiting issues. Key differentiators include its minimalistic and intuitive API, built-in TypeScript type definitions for enhanced developer experience, and clear methods such as `add`, `onIdle`, and `waitTillIdle` for effective task flow management. This library is particularly useful for scenarios requiring controlled execution of potentially resource-intensive async tasks, like API calls or data processing, ensuring stability and performance. While a specific release cadence is not explicitly stated, as a focused utility, updates are generally driven by bug fixes or minor enhancements rather than frequent feature additions.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates initializing a `PromiseQueue` with a specified concurrency, adding multiple asynchronous tasks, and then waiting for all tasks to complete before proceeding, logging their start and end.

import { PromiseQueue } from 'sb-promise-queue';

async function runConcurrentTasks() {
  const queue = new PromiseQueue({ concurrency: 3 }); // Allow 3 tasks to run concurrently
  const taskCount = 10;
  const results: string[] = [];

  console.log(`Starting ${taskCount} tasks with concurrency ${queue.options.concurrency}...`);

  for (let i = 1; i <= taskCount; i++) {
    queue.add(async () => {
      console.log(`  [Task ${i}] Started.`);
      // Simulate an async operation with varying duration
      await new Promise(resolve => setTimeout(resolve, Math.random() * 1000 + 500));
      const result = `Task ${i} completed.`;
      console.log(`  [Task ${i}] Finished.`);
      results.push(result);
      return result;
    });
  }

  // Wait for all tasks in the queue to finish
  await queue.waitTillIdle();
  console.log('All tasks finished!');
  console.log('Results:', results);
}

runConcurrentTasks();

view raw JSON →