Skip to content

Instantly share code, notes, and snippets.

@matheusb-comp
Created September 29, 2019 14:02
Show Gist options
  • Save matheusb-comp/7c9a95d568c4a769bc66090f09e25b9c to your computer and use it in GitHub Desktop.
Save matheusb-comp/7c9a95d568c4a769bc66090f09e25b9c to your computer and use it in GitHub Desktop.
Keep references of timeouts and promises to help during graceful shutdown
// Pending promises
let execs = []
// Timeouts waiting to run
let timeouts = []
const exec = (func, ...args) => {
const promise = func(...args).finally(() => {
// Cleanup after the promise settled (resolved or rejected)
execs = execs.filter((el) => el !== promise)
})
// Add the promise to the array so it may be cleaned up later
execs = [ ...execs, promise ]
return promise
}
const delayExec = (func, ms, ...args) => {
const timeout = setTimeout((callback, argsArr) => {
// Cleanup after the delay has completed
timeouts = timeouts.filter((el) => el !== timeout)
// Finally execute the function
exec(callback, ...argsArr)
}, ms, func, args)
// Add the timeout to the array so it may be cleaned up later
timeouts = [ ...timeouts, timeout ]
return timeout
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment