Created
September 29, 2019 14:02
-
-
Save matheusb-comp/7c9a95d568c4a769bc66090f09e25b9c to your computer and use it in GitHub Desktop.
Keep references of timeouts and promises to help during graceful shutdown
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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