Created
June 29, 2017 02:15
-
-
Save smac89/2cacab2633a66da330311f242825e5f7 to your computer and use it in GitHub Desktop.
Chained callbacks
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
interface ChainedCallback { | |
(): void; | |
} | |
class ChainedCallback { | |
private chain: Callback[]; | |
public static fromCallbacks(...cbs: Callback[]): ChainedCallback { | |
let chained = new ChainedCallback(); | |
cbs.forEach(chained.attach); | |
return chained; | |
} | |
public asPromise(): Promise<Error> { | |
return new Promise((resolve, reject) => { | |
try { | |
this(); | |
resolve(null); | |
} catch (e) { | |
reject(e); | |
} | |
}); | |
} | |
public attach(cb: Callback): ChainedCallback { | |
this.chain.push(cb); | |
return this; | |
} | |
public exec(): void { | |
if (this.chain.length) { | |
this.chain.first()(); | |
} | |
} | |
public execAll(): void { | |
this.chain.forEach(cb => cb()); | |
} | |
public execDetach(): ChainedCallback { | |
if (this.chain.length) { | |
this.chain.pop()(); | |
} | |
return this; | |
} | |
public detach(): Callback { | |
if (this.chain.length) { | |
return this.chain.pop(); | |
} | |
return null; | |
} | |
public detachAll(): void { | |
// https://stackoverflow.com/a/1232046/2089675 | |
this.chain.splice(0, this.chain.length); | |
} | |
public execDetachAll(): void { | |
// https://stackoverflow.com/a/1232046/2089675 | |
this.chain.splice(0, this.chain.length) | |
.forEach(cb => cb()); | |
} | |
constructor() { | |
Object.assign(this.execAll, this); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment