node-singleflight
v0.1.3
Published
provides a duplicate function call suppression
Readme
node-singleflight
Suppress duplicate function calls with the same key while one call is still in flight. Duplicate callers share the same result or rejection.
Install
npm install node-singleflightyarn add node-singleflightUsage
JavaScript using the existing CommonJS API:
const singleflight = require('node-singleflight')
async function example() {
return singleflight.Do('SomeKey', async () => {
const data = await doSomething()
return processData(data)
})
}The equivalent TypeScript version uses the declarations included with the package:
import { Do } from 'node-singleflight'
async function example(): Promise<ProcessedData> {
return Do('SomeKey', async () => {
const data = await doSomething()
return processData(data)
})
}API
Do(key, func)
Runs func once while the given key is in flight and returns a Promise for its result.
- Calls with the same key share the same result or rejection.
- Calls with different keys run independently.
- Keys use JavaScript
Mapidentity semantics; object keys match by reference. - The key is removed after fulfillment or rejection, so a later call can retry.
funcmay return a value, a Promise, or any Promise-like value.
func must eventually settle. If it never fulfills or rejects, calls using the same key will continue waiting. Apply a timeout or cancellation inside func when the underlying operation can hang.
