const PROMISE_STATE = {
STATE_PENDING: "pending",
STATE_FULLFILLED: "fullfilled",
STATE_REJECTED: "rejected"
};
class myPromise {
constructor(executor) {
this.value = null;
this.reason = null;
this.state = PROMISE_STATE.STATE_PENDING;
this.onFullfilledCallbacks = [];
this.onRejectedCallbacks = [];
try {
executor(this.resolve, this.reject);
} catch(e) {
this.reject(e);
}
}
resolve = value => {
if (this.state === PROMISE_STATE.STATE_PENDING) {
this.state = PROMISE_STATE.STATE_FULLFILLED;
this.value = value;
while(this.onFullfilledCallbacks.length) {
this.onFullfilledCallbacks.shift()(value);
}
}
}
reject = reason => {
if (this.state === PROMISE_STATE.STATE_PENDING) {
this.state = PROMISE_STATE.STATE_REJECTED;
this.reason = reason;
while(this.onRejectedCallbacks.length) {
this.onRejectedCallbacks.shift()(reason);
}
}
}
then(onFullfilled, onRejected) {
if (this.state === PROMISE_STATE.STATE_FULLFILLED) {
onFullfilled(this.value);
} else if (this.state === PROMISE_STATE.STATE_REJECTED) {
onRejected(this.reason);
} else if (this.state === PROMISE_STATE.STATE_PENDING) {
this.onFullfilledCallbacks.push(onFullfilled);
this.onRejectedCallbacks.push(onRejected);
}
}
}
const promise = new myPromise((resolve, reject) => {
reject("执行失败");
});
promise.then(value => {
console.log('resolve', value)
}, reason => {
console.log('reject', reason)
})
const promise1 = new myPromise((resolve, reject) => {
setTimeout(() => {
resolve('success')
}, 2000);
});
promise1.then(value => {
console.log(1)
console.log('resolve', value)
});
promise1.then(value => {
console.log(2)
console.log('resolve', value)
});