Giter VIP home page Giter VIP logo

promise-semaphore's Introduction

@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

API

Create an instance

const Semaphore = require('@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.

Example 1

const Semaphore = require('@chriscdn/promise-semaphore')
const semaphore = new Semaphore()

// using promises
semaphore.acquire()
	.then(() => {
		// This block executes once a lock has been acquired.  If already locked
		// then this block will wait and execute once all locks preceeding it have been
		// released.
	})
	.finally(() => {
		// release the lock permitting the next queued process to continue
		semaphore.release()
	})

// or, using async/await
await semaphore.acquire()

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

Example 2

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

async function downloadAndCache(url) {

	// cacheFilePath could be based on a hash of the url
	const cacheFilePath = getCacheFilePath(url)

	if (!await pathExists(cacheFilePath)) {
		await downloadToFile(url, cacheFilePath)
	}

	return cacheFilePath
}

This works until a process calls downloadAndCache() in short succession with the same url parameter. This can cause multiple simultaneous downloads that attempt to write to the same cached file.

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

const Semaphore = require('@chriscdn/promise-semaphore')
const semaphore = new Semaphore()

async function downloadAndCache(url) {

	await semaphore.acquire(url)

	// This block continues once a lock on url is acquired.  This permits
	// multiple simulataneous downloads for unique url values.

	try {
		const cacheFileName = getCacheFilePath(url)

		if (!await pathExists(cacheFilePath)) {
			await downloadToFile(url, cacheFilePath)	
		}

		return cacheFilePath

	} finally {
		semaphore.release(url)
	}
}

License

MIT

promise-semaphore's People

Contributors

chriscdn avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.