piggybacker
v2.0.0
Published
Async keyed job runner, piggyback on results from running jobs with the same key
Downloads
20
Readme
piggybacker
Async keyed job runner, piggyback on results from running jobs with the same key
Usage
import { piggyback } from 'piggybacker'
async function fetchJSON (url) {
const res = await window.fetch(url)
return res.json()
}
const piggyFetchJSON = piggyback(
fetchJSON,
// Given the args that will be passed to fetchJSON, generate a key so that if
// a second call is made while the first is in flight then the second will
// ALSO receive the results of the first, instead of having to make a
// separate request.
function getKey (url) {
return url
}
)
const results = await Promise.all([
// Multiple calls to piggyFetchJSON with the same URL _while_ a request is in
// progress will not send another request! Instead they'll wait on the results
// of the first.
piggyFetchJSON('https://example.org/data.json'),
piggyFetchJSON('https://example.org/data.json'),
piggyFetchJSON('https://example.org/data.json')
])
// fetchJSON called only ONCE!
API
piggyback(fn, getKey)
Create a new function that'll call fn
and piggyback on the results if called again.
fn
- the function to piggyback ongetKey
- a function called before each call tofn
that generates a key for the call. Two or more calls with the same key will be piggybacked
Contribute
Feel free to dive in! Open an issue or submit PRs.
License
MIT © Alan Shaw