Skip to content

Instantly share code, notes, and snippets.

@JamesBender
Forked from ericelliott/cancellable-wait.js
Created January 20, 2017 19:01
Show Gist options
  • Select an option

  • Save JamesBender/efcd3583f2651b03a882f4abf9519d4b to your computer and use it in GitHub Desktop.

Select an option

Save JamesBender/efcd3583f2651b03a882f4abf9519d4b to your computer and use it in GitHub Desktop.
Cancellable wait -- an ES6 promise example
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