const isFunction = target => typeof target === 'function';
class MyPromise {
_state = 'PENDING';
_result = null;
_fulfilledCallbacks = [];
_rejectedCallbacks = [];
constructor(handle) {
if (!isFunction(handle)) {
throw new Error('MyPromise must accept a function as a parameter')
}
try {
handle(this._resolve, this._reject)
} catch (err) {
this._reject(err)
}
}
_resolve = res => {
if (this._state !== 'PENDING') return;
this._state = 'FULFILLED';
this._result = res;
setTimeout(() => {
this._fulfilledCallbacks.forEach(cb => {
cb(res);
})
}, 0)
}
_reject = res => {
if (this._state !== 'PENDING') return;
this._state = 'REJECTED';
this._result = res;
setTimeout(() => {
this._rejectedCallbacks.forEach(cb => {
cb(res);
})
}, 0)
}
then = (onFulfilled, onRejected) => {
const { _value, _state } = this;
return new MyPromise((onFulfilledNext, onRejectedNext) => {
let fulfill = value => {
console.log(onFulfilled)
try {
if (!isFunction(onFulfilled)) {
onFulfilledNext(value);
} else {
let res = onFulfilled(value);
if (res instanceof MyPromise) {
res.then(onFulfilledNext, onRejectedNext);
} else {
onFulfilledNext(value);
}
}
} catch (err) {
onRejectedNext(err);
}
}
let reject = value => {
try {
if (!isFunction(onRejected)) {
onRejectedNext(value);
} else {
let res = onRejected(value);
if (res instanceof MyPromise) {
res.then(onFulfilledNext, onRejectedNext);
} else {
onFulfilledNext(value);
}
}
} catch (err) {
onRejectedNext(err);
}
}
switch (_state) {
case 'PENDING':
this._fulfilledCallbacks.push(fulfill)
this._rejectedCallbacks.push(reject)
break
case 'FULFILLED':
fulfill(_value);
break
case 'REJECTED':
reject(_value);
break
}
});
}
}
new MyPromise((resolve, reject) => {
resolve(1);
}).then((res) => {
console.log(123);
})
console