Skip to content

Instantly share code, notes, and snippets.

@kygx-legend
Forked from unscriptable/tiny Promise.js
Last active March 13, 2017 05:22
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kygx-legend/7002637 to your computer and use it in GitHub Desktop.
Save kygx-legend/7002637 to your computer and use it in GitHub Desktop.
// (c) copyright unscriptable.com / John Hann | LegendLee
// License MIT
// For more robust promises, see https://github.com/briancavalier/when.js.
// last edited by LegendLee(legendlee1314@gmail.com)
function Promise() {
this._thens = [];
}
Promise.prototype = {
then: function(onFulfilled, onRejected) {
this._thens.push({fulfill: onFulfilled, reject: onRejected});
return this;
},
fulfill: function(value) {
this._done('fulfill', value);
},
reject: function(error) {
this._done('reject', error);
},
_done: function(which, arg) {
// Cover and sync func `then()`.
this.then = which === 'fulfill' ?
function(fulfill, reject) {fulfill && fulfill(arg); return this;} :
function(fulfill, reject) {reject && reject(arg); return this;};
// Disallow multiple calls.
this.fulfill = this.reject =
function() {throw new Error('Promise already completed.');}
// Complete all async `then()`s.
var then, i = 0;
while (then = this._thens[i++]) {
then[which] && then[which](arg);
}
delete this._thens;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment