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

@chriscdn/promise-semaphore

v2.0.9

Published

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

Downloads

15,188

Readme

@chriscdn/promise-semaphore

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

Installing

Using npm:

npm install @chriscdn/promise-semaphore

Using yarn:

yarn add @chriscdn/promise-semaphore

Updating v1 to v2

Version 2 adds TypeScript and better inline documentation. The API remains the same, and doesn't introduce any breaking changes.

API

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). Use an integer value greater than one to limit how many times the code block can be simultaneously executing from separate iterations of the event loop.

Acquire a lock

semaphore.acquire([key]);

This returns a Promise, which resolves once a lock has been acquired. The key parameter is optional and permits the same Semaphore instance to be used in different contexts. See the second example.

Release a lock

semaphore.release([key]);

The release call should be executed from a finally block (whether using promises or a try/catch block) to guarantee it gets called.

Check if a lock can be acquired

semaphore.canAcquire([key]);

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

request function

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

This function reduces boilerplate when using acquire and release. It returns a promise, which resolves once fn has completed. It is functionally equivalent to:

try {
  await semaphore.acquire([key]);
  const results = await fn();
} finally {
  semaphore.release([key]);
}

See the examples below.

requestIfAvailable function

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

This is functionally equivalent to:

const results = semaphore.canAcquire([key] ?
  await semaphore.request(fn, [key]) :
  null

This is useful in situations when only one instance of a function block should run, while discarding other attempts to execute the block. E.g., a button is repeatedly clicked.

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,
    // then wait and execute once all preceeding locks have been released.
    //
    // do your critical stuff here
  })
  .finally(() => {
    // release the lock permitting the next queued block to continue
    semaphore.release();
  });

// or, using async/await
try {
  await semaphore.acquire();

  // do your critical stuff here
} finally {
  semaphore.release();
}

// or, using the request function
semaphore.request(() => {
  // do your critical stuff here
});

Example 2

Say you have an asynchronous function to download a file and save it to disk:

async function downloadAndSave(url) {
  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;
}

This works until a process calls downloadAndSave() multiple times in short succession with the same url. This can cause multiple simultaneous downloads that attempt to write to the same file at the same time.

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

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

async function downloadAndSave(url) {
  try {
    await semaphore.acquire(url);

    // This block continues once a lock on url is acquired.  This
    // permits multiple simulataneous 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);
  }
}

Alternatively, this can be accomplished with the request function:

async function downloadAndSave(url) {

  return semaphore.request(() => {
    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
  }, url)

}

License

MIT