Created
October 21, 2012 16:56
-
-
Save mkuklis/3927595 to your computer and use it in GitHub Desktop.
simple promise
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
function Promise(context) { | |
this.context = context || this; | |
this.success = []; | |
this.error = []; | |
} | |
Promise.prototype.then = function (success, error) { | |
if (success) { | |
if (this.resolved) { | |
success.apply(this.context, this.resolved); | |
} | |
else { | |
this.success.push(success); | |
} | |
} | |
if (error) { | |
if (this.rejected) { | |
error.apply(this.context, this.rejected); | |
} | |
else { | |
this.error.push(error); | |
} | |
} | |
return this; | |
}; | |
Promise.prototype.resolve = function () { | |
var callback; | |
this.resolved = arguments; | |
this.error = []; | |
while (callback = this.success.shift()) { | |
callback.apply(this.context, this.resolved); | |
} | |
}; | |
Promise.prototype.reject = function () { | |
var callback; | |
this.rejected = arguments; | |
this.success = []; | |
while (callback = this.error.shift()) { | |
callback.apply(this.context, this.rejected); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment