jimmydivvy
6/13/2015 - 2:20 PM

Basic promise implementation

Basic promise implementation

/* 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)