Last active
April 5, 2018 00:13
-
-
Save mgtitimoli/879fc9b3a9203e49e86186a759546def to your computer and use it in GitHub Desktop.
Yet another cancellation promise module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @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