Created
January 13, 2012 14:43
-
-
Save scttnlsn/1606568 to your computer and use it in GitHub Desktop.
Simple promise implementation for Node.js and the browser
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() { | |
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