Last active
October 8, 2019 08:06
-
-
Save ericelliott/7da732294d4c23c549aeff887e02fa82 to your computer and use it in GitHub Desktop.
Cancellable wait -- an ES6 promise example
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
const wait = ( | |
time, | |
cancel = Promise.reject() | |
) => new Promise((resolve, reject) => { | |
const timer = setTimeout(resolve, time); | |
const noop = () => {}; | |
cancel.then(() => { | |
clearTimeout(timer); | |
reject(new Error('Cancelled')); | |
}, noop); | |
}); | |
const shouldCancel = Promise.resolve(); // Yes, cancel | |
// const shouldCancel = Promise.reject(); // No cancel | |
wait(2000, shouldCancel).then( | |
() => console.log('Hello!'), | |
(e) => console.log(e) // [Error: Cancelled] | |
); |
This is not a cancellable Promise it's a Timeout on a Promise
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I like the way you extracted the pattern into a function.
The name
wait
seems ambiguous though. Naming things is hard.