Last active
August 29, 2015 14:20
-
-
Save Eyas/28382f47c2f3c7a926c4 to your computer and use it in GitHub Desktop.
Simple TypeScript 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
module simple { | |
export class Promise<T> { | |
public map<R>(func: (t: T) => R): Promise<R> { | |
var promise: Promise<R> = new Promise<R>(); | |
if (this.v !== undefined) promise.result(func(this.v)); | |
else if (this.e !== undefined) promise.result(this.e); | |
else { | |
this.tcb.push(t => { | |
promise.result(func(t)); | |
}); | |
this.ecb.push(e => { | |
promise.result(e); | |
}) | |
} | |
return promise; | |
} | |
public then<R>(func: (t: T) => Promise<R>): Promise<R> { | |
var promise: Promise<R> = new Promise<R>(); | |
if (this.v !== undefined) return func(this.v); // optimize since they are equivalent | |
else if (this.e !== undefined) promise.result(this.e); | |
else { | |
this.tcb.push(t => { | |
var res = func(t); | |
if (res.v !== undefined) promise.result(res.v); | |
else if (res.e !== undefined) promise.result(res.e); | |
else { | |
res.tcb.push(rt => { | |
promise.result(rt); | |
}); | |
res.ecb.push(et => { | |
promise.result(et); | |
}); | |
} | |
}); | |
this.ecb.push(e=> { | |
promise.result(e); | |
}); | |
} | |
return promise; | |
} | |
public result(r: Error|T): void { | |
if (this.e || this.v) { | |
throw new Error("result called twice."); | |
} | |
if (r instanceof Error) { | |
this.ecb.forEach(cb => cb(r)); | |
this.e = r; | |
} else { | |
this.tcb.forEach(cb => cb(<T>r)); | |
this.v = <T>r; | |
} | |
this.ecb = null; | |
this.tcb = null; | |
} | |
private tcb: ((t: T) => void)[] = []; | |
private ecb: ((e: Error) => void)[] = []; | |
private e: Error; | |
private v: T; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment