Created
March 15, 2016 08:29
-
-
Save martincik/ccd7ab902e312747833f to your computer and use it in GitHub Desktop.
Cancelable snippet
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 */ | |
'use strict'; | |
/** | |
* A Cancelable is a proxy for a function which supports cancelation. | |
* When a cancelable is called, it will pass its arguments to the underlying | |
* function, unless it is canceled in which case it will become a no-op. | |
* | |
* We need this as there's now way atm to cancel promise already running, | |
* so what were're doing here is changing the execution callback to empty | |
* callback. | |
* | |
* eg. | |
* c = cancelable(arg => doSomethingWithArg(arg)); | |
* c.cancel(); // "cancel" the promise so that doSomethingWithArg | |
* // is never called. | |
*/ | |
export default function cancelable(fn: Function) : Function { | |
let _fn = fn; | |
let cancelableFn:Function = (...args: any[]) => _fn(...args); | |
let cancelableInterface:Function = (...args) => cancelableFn(...args); | |
cancelableInterface.cancel = () => { | |
_fn = () => { }; | |
}; | |
return cancelableInterface; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment