Skip to content

Instantly share code, notes, and snippets.

@martincik
Created March 15, 2016 08:29
Show Gist options
  • Save martincik/ccd7ab902e312747833f to your computer and use it in GitHub Desktop.
Save martincik/ccd7ab902e312747833f to your computer and use it in GitHub Desktop.
Cancelable snippet
/* @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