Skip to content

Instantly share code, notes, and snippets.

@vanceingalls
Last active December 28, 2015 18:09
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 vanceingalls/7540614 to your computer and use it in GitHub Desktop.
Save vanceingalls/7540614 to your computer and use it in GitHub Desktop.
function Promise(){
this._callbacks = [];
}
Promise.prototype.resolve = function (data) {
if (typeof this._data !== 'undefined') {
// assuming console
console.error('This promise has already been resolved');
return;
}
this._data = data;
// execute all currently attached callbacks
while (this._callbacks.length) {
this._callbacks.shift().call(null, data);
}
}
Promise.prototype.success = function (cb) {
// execute callback immediately if promise is resolved
if (typeof this._data !== 'undefined') {
cb.call(null, this._data);
// otherwise store callback and wait
} else {
this._callbacks.push(cb);
}
// for chaining
return this;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment