Skip to content

Instantly share code, notes, and snippets.

@mgtitimoli
Last active April 5, 2018 00:13
Show Gist options
  • Save mgtitimoli/879fc9b3a9203e49e86186a759546def to your computer and use it in GitHub Desktop.
Save mgtitimoli/879fc9b3a9203e49e86186a759546def to your computer and use it in GitHub Desktop.
Yet another cancellation promise module
// @flow
type CancellablePromise<Result> = {
promise: Promise<Result>,
cancel: (reason?: string) => void
};
// $FlowFixMe: can not add custom properties to Error
const setCancelled = (error, cancelled) => Object.assign(error, {cancelled});
const createError = reason => setCancelled(new Error(reason), true);
const createControllerCancel = reject => reason => reject(createError(reason));
const createController = (): CancellablePromise<*> => {
let cancel;
const promise = new Promise((resolve, reject) => {
cancel = createControllerCancel(reject);
});
return {
// $FlowFixMe: flow is not detecting the assignment inside the promise
cancel,
promise
};
};
const createCancellable = <Result>(
promise: Promise<Result>
): CancellablePromise<Result> => {
const controller = createController();
return {
cancel: controller.cancel,
promise: Promise.race([
controller.promise,
promise.catch((error: Error) => {
throw setCancelled(error, false);
})
])
};
};
export default createCancellable;
export type {CancellablePromise};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment