Skip to content

Instantly share code, notes, and snippets.

@aocenas
Created July 2, 2014 08:42
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 aocenas/375405538c245271a271 to your computer and use it in GitHub Desktop.
Save aocenas/375405538c245271a271 to your computer and use it in GitHub Desktop.
var log = function log (e) {
console.log(e);
};
var Promise = function () {
this.resolved = false;
this.resolvedValue = null;
this.rejected = false;
this.rejectedValue = null;
};
Promise.prototype.then = function (okCb, errCb) {
this.okCb = okCb;
this.errCb = okCb;
this.nextPromise = new Promise();
if (this.resolved || this.rejected) {
this._fulfill();
}
return this.nextPromise;
};
Promise.prototype._fulfill = function () {
var val = this.resolved ? this.resolvedValue : this.rejectedValue;
var func = this.resolved ? this.okCb : this.errCb || log;
var that = this;
setTimeout(function () {
try {
var result = func(val);
if (result.then) {
result.then(function (val) {
that.nextPromise.resolve(result);
}, function (e) {
that.nextPromise.reject(result);
});
} else {
that.nextPromise.resolve(result);
}
} catch(e) {
that.nextPromise.reject(e);
}
}, 0);
};
Promise.prototype.resolve = function (val) {
this.resolved = true;
this.resolvedValue = val;
if (this.okCb) {
this._fulfill();
}
};
Promise.prototype.reject = function (val) {
this.rejected = true;
this.rejectedValue = val;
if (this.okCb) {
this._fulfill();
}
};
Promise.prototype.done = function () {
if (this.rejected) {
throw this.rejectedValue;
}
};
var Deferred = function () {
this.promise = new Promise();
};
Deferred.prototype.resolve = function (val) {
this.promise.resolve(val);
};
Deferred.prototype.reject = function (val) {
this.promise.reject(val);
};
var Q = {
defer: function () {
return new Deferred();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment