Skip to content

Instantly share code, notes, and snippets.

@char0n
Created January 25, 2017 09:36
Show Gist options
  • Save char0n/374e681d39b2940c4b01a3351ae7f8bc to your computer and use it in GitHub Desktop.
Save char0n/374e681d39b2940c4b01a3351ae7f8bc to your computer and use it in GitHub Desktop.
import { isObject, isFunction, curry } from 'lodash/fp';
export function isThenable(promise) {
return isObject(promise) && isFunction(promise.then);
}
export function isCancellable(promise) {
return isThenable(promise) && isFunction(promise.cancel);
}
export function isCancelled(promise) {
return isCancellable(promise) && isFunction(promise.isCancelled) && promise.isCancelled();
}
export function hasFinallyInterface(promise) {
return isThenable(promise) && isFunction(promise.finally);
}
export function cancel(promise) {
if (!isCancellable(promise)) { return false }
promise.cancel();
return true;
}
export const onFinally = curry((callback, promise) => {
if (!hasFinallyInterface(promise)) { return promise }
return promise.finally(callback);
});
export const onCancel = curry((callback, promise) => {
if (!isCancellable(promise)) { return promise }
return onFinally(() => {
if (isCancelled(promise)) { callback() }
})(promise);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment