UNPKG

node-singleflight

Version:

provides a duplicate function call suppression

56 lines (39 loc) 1.47 kB
# 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 ```sh npm install node-singleflight ``` ```sh yarn add node-singleflight ``` ## Usage JavaScript using the existing CommonJS API: ```js 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: ```ts 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 `Map` identity semantics; object keys match by reference. - The key is removed after fulfillment or rejection, so a later call can retry. - `func` may 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.