Skip to content

Instantly share code, notes, and snippets.

@lenconda
Last active January 15, 2020 08:37
Show Gist options
  • Save lenconda/817202511b98173a133fd56a583218c5 to your computer and use it in GitHub Desktop.
Save lenconda/817202511b98173a133fd56a583218c5 to your computer and use it in GitHub Desktop.
promise implementation
function Promisible(executor) {
var _this = this;
_this.status = 'pending';
_this.result = null;
_this.reason = null;
_this.resolvedCallbacks = [];
_this.rejectedCallbacks = [];
function resolve(result) {
if (_this.status === 'pending') {
_this.result = result;
_this.status = 'fulfilled';
_this.resolvedCallbacks.forEach(fn => fn());
}
}
function reject(reason) {
if (_this.status === 'pending') {
_this.reason = reason;
_this.status = 'rejected';
_this.rejectedCallbacks.forEach(fn => fn());
}
}
executor(resolve, reject);
}
Promisible.prototype.then = function(onfulfilled, onrejected) {
var _this = this;
if (_this.status === 'resolved'){
onfulfilled(_this.value);
}
if (_this.status === 'rejected'){
onrejected(_this.reason);
}
if (_this.status === 'pending') {
_this.resolvedCallbacks.push(function() {
onfulfilled(_this.result);
});
_this.rejectedCallbacks.push(function() {
onrejected(_this.reason);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment