Skip to content

Instantly share code, notes, and snippets.

@avanishgiri
Created November 21, 2013 04:59
Show Gist options
  • Save avanishgiri/7576313 to your computer and use it in GitHub Desktop.
Save avanishgiri/7576313 to your computer and use it in GitHub Desktop.
function Promise(){
this.callbacks = [];
this.value = undefined;
}
Promise.prototype.success = function(callback){
this.callbacks.push(callback);
if(this.value)
this.execute_callbacks();
}
Promise.prototype.execute_callbacks = function(){
var that = this;
this.callbacks.forEach(function(callback){
callback(that.value);
});
}
Promise.prototype.resolve = function(value){
if(this.value)
console.log("Error! Promise already resolved to value.");
else {
this.value = value;
if(this.callbacks)
this.execute_callbacks();
}
}
var foo = new Promise();
var bar = new Promise();
foo.resolve('hello');
setTimeout(function(){
bar.resolve('world');
}, 500);
foo.success(function(result){
console.log(result);
});
foo.success(function(result){
console.log("second callback");
});
bar.success(function(result){
console.log(result);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment