Skip to content

Instantly share code, notes, and snippets.

@ericelliott
Last active October 8, 2019 08:06
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ericelliott/7da732294d4c23c549aeff887e02fa82 to your computer and use it in GitHub Desktop.
Save ericelliott/7da732294d4c23c549aeff887e02fa82 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);
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]
);
@gunar
Copy link

gunar commented Jan 20, 2017

I like the way you extracted the pattern into a function.
The name wait seems ambiguous though. Naming things is hard.

@millsp
Copy link

millsp commented Sep 18, 2018

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