Skip to content

Instantly share code, notes, and snippets.

@mniak
Last active July 19, 2016 11:15
Show Gist options
  • Save mniak/8e157583965b7af00d5ef975b9569cff to your computer and use it in GitHub Desktop.
Save mniak/8e157583965b7af00d5ef975b9569cff to your computer and use it in GitHub Desktop.
ThenElse for TypeScript - a kind of promise that does not throw an error when there is no catch
// https://gist.github.com/andregsilv/8e157583965b7af00d5ef975b9569cff
export class ThenElse<T> {
private done: boolean;
private value: any;
private failure: boolean;
private thenCallbacks = new Array<(value: T) => void>();
private elseCallbacks = new Array<(value: any) => void>();
constructor(task: (resolve: (value: T) => void, reject: (reason: any) => void) => void) {
this.done = false;
this.value = null;
this.failure = false;
task(x => this.resolve(x), x => this.reject(x));
}
private resolve(value: T) {
if (!this.done) {
this.done = true;
this.failure = false;
this.value = value;
for (let cb of this.thenCallbacks) cb(this.value);
}
}
private reject(value: any) {
if (!this.done) {
this.done = true;
this.failure = true;
this.value = value;
for (let cb of this.elseCallbacks) cb(this.value);
}
}
then(callback: (value: T) => void) {
if (!this.done) this.thenCallbacks.push(callback);
else if (!this.failure) callback(this.value);
return this;
}
else(callback: (result: any) => void) {
if (!this.done) this.elseCallbacks.push(callback);
else if (this.failure) callback(this.value);
return this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment