{"id":16207,"library":"sb-promise-queue","title":"Promise-Queue","description":"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.","status":"active","version":"2.1.1","language":"javascript","source_language":"en","source_url":"https://github.com/steelbrain/promise-queue","tags":["javascript","Promise","queue","typescript"],"install":[{"cmd":"npm install sb-promise-queue","lang":"bash","label":"npm"},{"cmd":"yarn add sb-promise-queue","lang":"bash","label":"yarn"},{"cmd":"pnpm add sb-promise-queue","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The library primarily uses named exports. For modern Node.js and TypeScript projects, ES module `import` syntax is recommended. Direct CommonJS `require` may not work as expected in an ES module context.","wrong":"const PromiseQueue = require('sb-promise-queue');","symbol":"PromiseQueue","correct":"import { PromiseQueue } from 'sb-promise-queue';"},{"note":"When importing types like `Options` in TypeScript, use `import type` for clarity and to ensure it's removed during compilation, preventing potential runtime issues in environments that don't support type imports natively.","wrong":"import { Options } from 'sb-promise-queue';","symbol":"Options","correct":"import { type Options, PromiseQueue } from 'sb-promise-queue';"},{"note":"For legacy CommonJS environments (e.g., older Node.js versions or specific build setups), named exports can be destructured from the `require` call. However, this is not the primary recommended import method for new projects.","symbol":"PromiseQueue (CommonJS fallback)","correct":"const { PromiseQueue } = require('sb-promise-queue');"}],"quickstart":{"code":"import { PromiseQueue } from 'sb-promise-queue';\n\nasync function runConcurrentTasks() {\n  const queue = new PromiseQueue({ concurrency: 3 }); // Allow 3 tasks to run concurrently\n  const taskCount = 10;\n  const results: string[] = [];\n\n  console.log(`Starting ${taskCount} tasks with concurrency ${queue.options.concurrency}...`);\n\n  for (let i = 1; i <= taskCount; i++) {\n    queue.add(async () => {\n      console.log(`  [Task ${i}] Started.`);\n      // Simulate an async operation with varying duration\n      await new Promise(resolve => setTimeout(resolve, Math.random() * 1000 + 500));\n      const result = `Task ${i} completed.`;\n      console.log(`  [Task ${i}] Finished.`);\n      results.push(result);\n      return result;\n    });\n  }\n\n  // Wait for all tasks in the queue to finish\n  await queue.waitTillIdle();\n  console.log('All tasks finished!');\n  console.log('Results:', results);\n}\n\nrunConcurrentTasks();","lang":"typescript","description":"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."},"warnings":[{"fix":"Always ensure to `await queue.waitTillIdle()` when you need a guarantee that all tasks in the queue have finished their execution before proceeding with dependent code.","message":"Forgetting to `await queue.waitTillIdle()` will cause your script or subsequent logic to execute before all queued asynchronous tasks have completed, potentially leading to incomplete operations or race conditions.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always wrap the asynchronous logic inside your `add` callback with `try...catch` blocks or attach a `.catch()` handler to any promises returned, ensuring robust error handling for individual tasks.","message":"Tasks added to the queue via `add(callback)` execute the `callback` function. If the promise returned by `callback` rejects and this rejection is not handled internally within the callback, it will result in an unhandled promise rejection error that might not halt other tasks but will break your process if unhandled globally.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"For scenarios involving an exceptionally high number of tasks, consider implementing a mechanism to batch your task additions to the queue, or monitor memory usage closely to prevent resource exhaustion.","message":"The `concurrency` option limits the number of *currently running* promises, not the total number of tasks that can be added to the queue. Adding an extremely large number of tasks (e.g., millions) to a queue with very low concurrency can lead to high memory consumption as all tasks await their turn.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Ensure you are using the correct ES module named import: `import { PromiseQueue } from 'sb-promise-queue';`. If in a CommonJS environment, use `const { PromiseQueue } = require('sb-promise-queue');`.","cause":"Attempting to use `new PromiseQueue()` without correctly importing it from the module, or when the `require` call in a CommonJS context did not properly destructure the named export.","error":"TypeError: PromiseQueue is not a constructor"},{"fix":"Modify the `async` callback passed to `queue.add()` to include error handling. For example: `queue.add(async () => { try { await someAsyncOp(); } catch (error) { console.error('Task failed:', error); } });`","cause":"An asynchronous task (a promise) within a callback added to the queue rejected, and this rejection was not explicitly caught by a `.catch()` block or `try...catch` statement within that specific task's execution.","error":"UnhandledPromiseRejectionWarning: Unhandled promise rejection."},{"fix":"First, ensure the package is installed: `npm install sb-promise-queue`. If the error persists in an ES module environment (`\"type\": \"module\"` in `package.json`), verify your Node.js version supports ES modules or check for incorrect `tsconfig.json` module settings if using TypeScript.","cause":"The package `sb-promise-queue` is either not installed, or your project's module resolution settings (e.g., for ES modules vs. CommonJS) are incorrect.","error":"Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'sb-promise-queue' imported from ..."}],"ecosystem":"npm"}