Skip to content

Instantly share code, notes, and snippets.

@scttnlsn
Created January 13, 2012 14:43
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 scttnlsn/1606568 to your computer and use it in GitHub Desktop.
Save scttnlsn/1606568 to your computer and use it in GitHub Desktop.
Simple promise implementation for Node.js and the browser
(function() {
if (typeof module !== 'undefined' && module.exports) {
module.exports = Promise;
} else {
this.Promise = Promise;
}
function Promise(context) {
this.context = context || this;
this.callbacks = [];
this.resolved = undefined;
};
Promise.prototype.then = function(callback) {
if (this.resolved) {
callback.apply(this.context, this.resolved);
} else {
this.callbacks.push(callback);
}
};
Promise.prototype.resolve = function() {
if (this.resolved) throw new Error('Promise already resolved');
var callback;
this.resolved = arguments;
while (callback = this.callbacks.shift()) {
callback.apply(this.context, this.resolved);
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment