Created
November 1, 2015 12:30
-
-
Save robertknight/857d263dd4a68206da79 to your computer and use it in GitHub Desktop.
Cancelable callbacks for promises
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
/** | |
* A Pipe is a proxy for a function which supports cancelation. | |
* When a pipe is called, it will pass its arguments to the underlying | |
* function, unless it is canceled in which case it will become a no-op. | |
* | |
* Pipes are useful as a way to cancel promise callbacks by wrapping | |
* the fulfilment or rejection handler. | |
* | |
* eg. | |
* aPipe = pipe(arg => doSomethingWithArg(arg)); | |
* aPromise.then(aPipe); | |
* aPipe.cancel(); // "cancel" the promise so that doSomethingWithArg | |
* // is never called. | |
*/ | |
export interface Pipe { | |
(...args: any[]): void; | |
cancel(): void; | |
} | |
export default function pipe(fn: Function) { | |
let pipeFn: Pipe | Function = (...args: any[]) => { | |
fn(...args); | |
}; | |
let pipe = pipeFn as Pipe; | |
pipe.cancel = () => { | |
fn = () => { }; | |
}; | |
return pipe; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment