@chriscdn/promise-semaphore

中文文档
4.0.1发布于 2026/09/14MITTypeScriptES Module零依赖近 30 天下载 6709

Limit or throttle the simultaneous execution of asynchronous code in separate iterations of the event loop.

原始使用文档
文档目录15 节
  1. Installing
  2. Version 3
  3. API - Semaphore
  4. Create an instance
  5. Acquire a lock
  6. Release a lock
  7. Check if a lock can be acquired
  8. count
  9. request method
  10. requestIfAvailable method
  11. Example 1
  12. Example 2
  13. API - GroupSemaphore
  14. Example
  15. License

@chriscdn/promise-semaphore

Limit or throttle the concurrent execution of asynchronous code in separate iterations of the event loop.

Installing

Using npm:

npm install @chriscdn/promise-semaphore

Version 3

Version 3 introduces two main changes:

  • A new GroupSemaphore class has been added. It allows multiple tasks within the same group (identified by a key) to run concurrently while ensuring that only one group's tasks are active at a time. See documenation below for details.
  • The default export has been replaced with a named export.

Change:

import Semaphore from "@chriscdn/promise-semaphore";

to:

import { Semaphore } from "@chriscdn/promise-semaphore";

API - Semaphore

Create an instance

import { Semaphore } from "@chriscdn/promise-semaphore";
const semaphore = new Semaphore([maxConcurrent]);

The maxConcurrent parameter is optional and defaults to 1 (making it an exclusive lock or binary semaphore). An integer greater than 1 can be used to allow multiple concurrent executions from separate iterations of the event loop.

Acquire a lock

semaphore.acquire([options]);

This method returns a Promise that resolves when the lock is acquired.

The options parameter is optional and can be:

  • A key (string or number): This lets a single Semaphore instance manage locks in different contexts (see the second example for key usage).
  • An object with the following properties (all optional):
    • key (string or number): Functions the same as above.
    • priority (number): Determines the order in which queued requests are processed. Higher values are processed first.

Release a lock

semaphore.release([key]);

The release method should be called within a finally block (whether using promises or a try/catch block) to ensure the lock is released. It's crucial to call release with the same key the lock was acquired with.

Check if a lock can be acquired

semaphore.canAcquire([key]);

This synchronous method returns true if a lock can be immediately acquired, and false otherwise.

count

semaphore.count([key]);

This function is synchronous, and returns the current number of locks.

request method

const results = await semaphore.request(fn [, options]);

This function reduces boilerplate when using acquire and release. It returns a promise that resolves when fn completes. It is functionally equivalent to:

try {
  await semaphore.acquire([options]);
  return await fn();
} finally {
  semaphore.release([key]);
}

requestIfAvailable method

const results = await semaphore.requestIfAvailable(fn [, options]);

This is functionally equivalent to:

return semaphore.canAcquire([key])
  ? await semaphore.request(fn, [options])
  : null;

This is useful in scenarios where only one instance of a function block should run while discarding additional attempts. For example, handling repeated button clicks.

Example 1

import { Semaphore } from "@chriscdn/promise-semaphore";
const semaphore = new Semaphore();

// Using promises
semaphore
  .acquire()
  .then(() => {
    // This block executes once a lock is acquired.
    // If already locked, it waits and executes after all preceding locks are released.
    //
    // Critical operations
  })
  .finally(() => {
    // The lock is released, allowing the next queued block to proceed.
    semaphore.release();
  });

// Using async/await
try {
  await semaphore.acquire();

  // Critical operations
} finally {
  semaphore.release();
}

// Using the request function
await semaphore.request(() => {
  // Critical operations
});

Example 2

Consider an asynchronous function that downloads a file and saves it to disk:

const downloadAndSave = async (url) => {
  const filePath = urlToFilePath(url);

  if (await pathExists(filePath)) {
    // The file is already on disk, so no action is required.
    return filePath;
  }

  await downloadAndSaveToFilepath(url, filePath);
  return filePath;
};

This approach works as expected until downloadAndSave() is called multiple times in quick succession with the same url. Without control, it could initiate simultaneous downloads that attempt to write to the same file at the same time.

This issue can be resolved by using a Semaphore with the key parameter:

import { Semaphore } from "@chriscdn/promise-semaphore";
const semaphore = new Semaphore();

const downloadAndSave = async (url) => {
  try {
    await semaphore.acquire(url);

    // This block continues once a lock on url is acquired. This
    // permits multiple simultaneous downloads for different urls.

    const filePath = urlToFilePath(url);

    if (await pathExists(filePath)) {
      // the file is on disk, so no action is required
    } else {
      await downloadAndSaveToFilepath(url, filePath);
    }

    return filePath;
  } finally {
    semaphore.release(url);
  }
};

The same outcome can be achieved by using the request function:

const downloadAndSave = (url) => {
  return semaphore.request(async () => {
    const filePath = urlToFilePath(url);

    if (await pathExists(filePath)) {
      // The file is already on disk, so no action is required.
    } else {
      await downloadAndSaveToFilepath(url, filePath);
    }
    return filePath;
  }, url);
};

API - GroupSemaphore

The GroupSemaphore class manages a semaphore for different groups of tasks. A group is identified by a key, and the semaphore ensures that only one group can run its tasks at a time. The tasks within a group can run concurrently.

The GroupSemaphore class exposes acquire and release methods, which have the same interface as Semaphore. The only difference is that the key parameter is required.

Example

import { GroupSemaphore } from "@chriscdn/promise-semaphore";

const groupSemaphore = new GroupSemaphore();

const RunA = async () => {
  try {
    await groupSemaphore.acquire("GroupA");

    // Perform asynchronous operations for group A
  } finally {
    groupSemaphore.release("GroupA");
  }
};

const RunB = async () => {
  try {
    await groupSemaphore.acquire("GroupB");

    // Perform asynchronous operations for group B
  } finally {
    groupSemaphore.release("GroupB");
  }
};

This setup allows RunA to be called multiple times, and will run concurrently. However, calling RunB will wait until all GroupA tasks are completed before acquiring the lock for GroupB. As soon as GroupB acquires the lock, any subsequent calls to RunA will wait until GroupB releases the lock before it executes.

License

MIT

版本与发布记录

@chriscdn/promise-semaphore 共发布 25 个版本,首次发布于 2020/04/14;过去 12 个月发布了 3 个版本。

版本发布日期距今
4.0.1latest2026/09/141 个月前
4.0.02026/02/218 个月前
3.1.32026/02/208 个月前
3.1.22025/11/031 年前
3.1.12025/08/271.2 年前
3.0.12025/05/051.5 年前

关于 @chriscdn/promise-semaphore 的常见问题

@chriscdn/promise-semaphore 是什么?

Limit or throttle the simultaneous execution of asynchronous code in separate iterations of the event loop.

如何安装 @chriscdn/promise-semaphore?

在项目目录运行 npm install @chriscdn/promise-semaphore,或使用 pnpm add / yarn add / bun add。

@chriscdn/promise-semaphore 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@chriscdn/promise-semaphore 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@chriscdn/promise-semaphore 可以商用吗?

@chriscdn/promise-semaphore 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@chriscdn/promise-semaphore 的下载量有多少?

根据 npm 官方下载统计,@chriscdn/promise-semaphore 在 2026/10/10 – 2026/11/08 这 30 天内被下载 6,709 次,日均约 224 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@chriscdn/promise-semaphore 还在维护吗?

最新版本 4.0.1 发布于 2026/09/14(1 个月前);至今共发布 25 个版本,其中过去 12 个月发布了 3 个;首次发布于 2020/04/14。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。