Skip to content

Instantly share code, notes, and snippets.

@johnwahba
Last active December 27, 2015 00:29
Show Gist options
  • Save johnwahba/7238545 to your computer and use it in GitHub Desktop.
Save johnwahba/7238545 to your computer and use it in GitHub Desktop.
Basic promise implementation
Promise = function(){
this.result = undefined;
this.complete = false
this.failure = false;
this.onFailure = [];
this.onSuccess = [];
};
Promise.prototype.resolve = function(fnResult){
if (this.complete){
throw "Already resolved";
}
try
{
this.result = fnResult;
this.complete = true
for(var i = 0; i < this.onSuccess.length; i++){
this.onSuccess.shift()(fnResult);
}
}
catch(err)
{
this.failure = true;
for(var i = 0; i < this.onFailure.length; i++){
this.onFailure.shift()(err);
}
}
};
Promise.prototype.success = function(fn){
if(this.complete){
return fn(this.result);
} else {
this.onSuccess.push(fn);
}
};
Promise.prototype.error = function(fn){
if(this.failure === true){
return fn(this.result);
} else {
this.onFailure.push(fn);
}
};
var foo = new Promise();
var bar = new Promise();
foo.resolve('hello');
setTimeout(function(){
bar.resolve('world');
}, 500);
foo.success(function(result){
console.log(result);
});
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