Last active
January 15, 2020 08:37
-
-
Save lenconda/817202511b98173a133fd56a583218c5 to your computer and use it in GitHub Desktop.
promise implementation
This file contains hidden or 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 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