node-singleflight
Version:
provides a duplicate function call suppression
50 lines (42 loc) • 996 B
JavaScript
const flights = new Map()
// Do executes and returns the results of the given function, making
// sure that only one execution is in-flight for a given key at a
// time. If a duplicate comes in, the duplicate caller waits for the
// original to complete and receives the same results.
//
// Copy from golang pkg sync/singleflight
//
function Do (key, func) {
if (flights.has(key)) {
return flights.get(key)
}
let resolveOperation
let rejectOperation
const operation = new Promise((resolve, reject) => {
resolveOperation = resolve
rejectOperation = reject
})
const cleanup = () => {
if (flights.get(key) === flight) {
flights.delete(key)
}
}
const flight = operation.then(
(value) => {
cleanup()
return value
},
(error) => {
cleanup()
throw error
}
)
flights.set(key, flight)
try {
resolveOperation(func())
} catch (error) {
rejectOperation(error)
}
return flight
}
module.exports = Do