Skip to content

Instantly share code, notes, and snippets.

@ericelliott
Created January 23, 2017 02:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ericelliott/ac7a019137adc70512fc16e6da55bde9 to your computer and use it in GitHub Desktop.
Save ericelliott/ac7a019137adc70512fc16e6da55bde9 to your computer and use it in GitHub Desktop.
Speculation: Cancellable promise implementation. Maintained production version here: https://github.com/ericelliott/speculation
// HOF Wraps the native Promise API
// to add take a shouldCancel promise and add
// an onCancel() callback.
const speculation = (
fn,
cancel = Promise.reject() // Don't cancel by default
) => new Promise((resolve, reject) => {
const noop = () => {};
const onCancel = (
handleCancel
) => cancel.then(
handleCancel,
// Ignore expected cancel rejections:
noop
)
// handle onCancel errors
.catch(e => reject(e))
;
fn(resolve, reject, onCancel);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment