Last active
August 29, 2015 14:23
-
-
Save jimmydivvy/ab0a759eb69cf3fbba48 to your computer and use it in GitHub Desktop.
Basic promise implementation
This file contains hidden or 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
/* Very basic promise implementation */ | |
class Promise { | |
observers: []; | |
value: T; | |
resolved: Boolean; | |
constructor(){ | |
this.observers = []; | |
this.resolved = false; | |
this.value = undefined; | |
} | |
// onSuccess :: Promise t -> (t -> ()) -> () | |
onSuccess(cb){ | |
if( this.resolved ) | |
cb(this.value) | |
else | |
this.observers.push(cb) | |
} | |
// resolve :: Promise t -> t -> () | |
resolve(value){ | |
this.value = value; | |
this.resolved = true; | |
this.observers.forEach(obs => obs(value)) | |
} | |
// map :: Promise t -> (t -> u) -> Promise u | |
map(fn){ | |
var p = new Promise() | |
this.onSuccess( result => p.resolve(fn(result))) | |
return p; | |
} | |
// bind :: Promise t -> (t -> Promise u) -> Promise u | |
bind(fn){ | |
var p = new Promise() | |
this.onSuccess( result => fn(result).onSuccess( r => p.resolve(r))) | |
return p; | |
} | |
} | |
function later(delay, value){ | |
var p = new Promise(); | |
setTimeout( () => p.resolve(value), delay) | |
return p; | |
} | |
var p1 = later(100, 5) | |
.map(x => x * 2) | |
.map( x => x + "!" ) | |
var p2 = p1 | |
.bind( x => later(200, x + ' - more')) | |
.bind( x => later(300, x + ' !!!')) | |
p1.onSuccess(r => console.log("a1: ", r)) | |
p2.onSuccess(r => console.log("a2: ", r)) | |
setTimeout( () => p1.onSuccess(r => console.log("b1: ", r)), 1000) | |
setTimeout( () => p2.onSuccess(r => console.log("b2: ", r)), 1000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment