Skip to content

Instantly share code, notes, and snippets.

@primitiveshaun
Forked from ericelliott/speculation.js
Created October 8, 2019 08:05
Show Gist options
  • Save primitiveshaun/88ef094375e2b1076a6979f5e5533f89 to your computer and use it in GitHub Desktop.
Save primitiveshaun/88ef094375e2b1076a6979f5e5533f89 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