Skip to content

Instantly share code, notes, and snippets.

@addyosmani
Forked from unscriptable/tiny Promise.js
Created February 7, 2011 06:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save addyosmani/814065 to your computer and use it in GitHub Desktop.
Save addyosmani/814065 to your computer and use it in GitHub Desktop.
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;
}
};
@unscriptable
Copy link

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. :)

@addyosmani
Copy link
Author

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