Created
January 25, 2017 09:36
-
-
Save char0n/374e681d39b2940c4b01a3351ae7f8bc to your computer and use it in GitHub Desktop.
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
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