-
-
Save addyosmani/814065 to your computer and use it in GitHub Desktop.
This file contains 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 () { | |
this._thens = []; | |
} | |
Promise.prototype = { | |
then: function (resolve, reject) { | |
// capture calls to then() | |
this._thens.push({ resolve: resolve, reject: reject }); | |
}, | |
resolve: function (val) { this._complete('resolve', val); }, | |
reject: function (ex) { this._complete('reject', ex); }, | |
_complete: function (which, arg) { | |
// switch over to sync then() | |
this.then = which === 'resolve' ? | |
function (resolve, reject) { resolve(arg); } : | |
function (resolve, reject) { reject(arg); }; | |
// complete all async then()s | |
var aThen, i = 0; | |
while (aThen = this._thens[i++]) { aThen[which] && aThen[which](arg); } | |
delete this._thens; | |
} | |
}; |
Thanks for letting me know! Appreciate the update :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just after you forked this, I added a line that will throw an exception if the resolve() or reject() methods are called more than once. That should save some tedious debug time. :)