Norse Power Metal

    @chriscdn/promise-semaphore

    1.0.9 • Public • Published

    @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.

    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 where only one instance of a function block should run at a time, while discarding other attempts to execute the block. E.g., a button that is being repeatedly tapped or clicked by the user.

    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 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 downloadToFile(url, filePath)
    	}
    
    	return filePath
    }

    This works until a process calls downloadAndSave() in short succession with the same url parameter. This can cause multiple simultaneous downloads that attempt to write to the same 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 downloadAndSave(url) {
    
    	try {
    	
    		await semaphore.acquire(url)
    
    		// This block continues once a lock on url is acquired.  This permits
    		// multiple simulataneous downloads for each unique url.
    	
    		const filePath = urlToFilePath(url)
    	
    		if (await pathExists(filePath)) {
    			// the file is on disk, so no action is required
    		} else {
    			await downloadToFile(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 downloadToFile(url, filePath)
    		}
    	
    		return filePath	
    	}, url)
    
    }

    License

    MIT

    Install

    npm i @chriscdn/promise-semaphore

    DownloadsWeekly Downloads

    577

    Version

    1.0.9

    License

    MIT

    Unpacked Size

    12.6 kB

    Total Files

    8

    Last publish

    Collaborators

    • chriscdn