const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECT = 'reject';
function myPromise(fn) {
let _this = this;
this.state = PENDING;
this.value = undefined;
this.reason = undefined;
this.onFulfillList = [];
this.onRejectList = [];
function reslove(value) {
_this.state = FULFILLED;
_this.value = value;
_this.onFulfillList.forEach((item) = > item(value));
}
function reject(reason) {
_this.state = REJECT;
_this.reason = reason;
_this.onRejectList.forEach((item) = > item(reason));
}
try {
fn(reslove, reject);
} catch (error) {
reject(error);
}
myPromise.prototype.then = function(res, rej) {
if (this.state === 'fulfilled') {
typeof res === 'function' && res(this.value);
}
if (this.state === 'reject') {
typeof rej === 'function' && rej(this.reason);
}
if (this.state === 'pending') {
typeof res === 'function' && this.onFulfillList.push(res);
typeof rej === 'function' && this.onRejectList.push(rej); }};Copy the code
Reference zhuanlan.zhihu.com/p/144058361 if any infringement, please contact me to delete