Skip to content

Instantly share code, notes, and snippets.

@slikts
Last active September 3, 2018 14:09
Show Gist options
  • Save slikts/4b4ae07adf52feac2c1a34e422f4ffd2 to your computer and use it in GitHub Desktop.
Save slikts/4b4ae07adf52feac2c1a34e422f4ffd2 to your computer and use it in GitHub Desktop.
const abortError = new Error(`Aborted`)
const promisifySignal = signal =>
signal.aborted
? Promise.reject(abortError)
: new Promise(
(_, reject) =>
void signal.addEventListener(`abort`, () => void reject(abortError), { once: true }),
)
const sleep = (delay, ...args) => new Promise(resolve => setTimeout(resolve, delay, ...args))
const cancelableSleep = (delay, signal, ...args) =>
Promise.race([promisifySignal(signal), sleep(delay, ...args)])
const sleep = (delay, signal = null) =>
signal !== null && signal.aborted
? Promise.reject(new Error(`Aborted`))
: new Promise((resolve, reject) => {
const timeout = setTimeout(resolve, delay)
if (signal !== null) {
signal.addEventListener(`abort`, () => {
clearTimeout(timeout)
reject(new Error(`Aborted`))
})
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment