-
-
Save JamesBender/efcd3583f2651b03a882f4abf9519d4b to your computer and use it in GitHub Desktop.
Cancellable wait -- an ES6 promise example
This file contains hidden or 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); | |
| cancel.then(() => { | |
| clearTimeout(timer); | |
| reject(new Error('Cancelled')); | |
| }); | |
| }); | |
| 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] | |
| ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment