let pedding = 'pendding';
let fulfilled = 'fulfilled';
let rejected = 'rejected';
class myPromise {
state = pedding
value = undefined
onFulfills = []
onRejects = []
constructor (express) {
if (typeof express !== 'function') {
throw Error('myPromise接收参数必须是一个函数');
}
express(this.resolve.bind(this), this.reject.bind(this));
}
resolve (value) {
if (value instanceof myPromise) {
value.then(resole, reject);
}
setTimeout(() => {
if (this.state === pedding) {
this.state = fulfilled;
this.value = value;
while (this.onFulfills.length) {
this.onFulfills.shift()(this.value)
}
}
})
}
reject (value) {
if (value instanceof myPromise) {
value.then(resole, reject);
}
setTimeout(() => {
if (this.state === pedding) {
this.state = rejected;
this.value = value;
while (this.onRejects.length) {
this.onRejects.shift()(this.value)
}
}
})
}
then (onResolve, onReject) {
let {state, value} = this;
return new myPromise((resolve, reject) => {
onResolve = typeof onResolve === 'function' ? onResolve : (value) => value
onReject = typeof onReject === 'function' ? onReject : (value) => value
const fulfillFun = (value) => {
try {
let x = onResolve(value);
if (x === this) {
throw Error('不能返回promise实例自身')
}
if (x instanceof myPromise) {
x.then(resolve, reject)
} else {
resolve(x);
}
} catch (err) {
reject(err)
}
}
const rejectFun = (value) => {
try {
let x = onReject(value);
if (x === this) {
throw Error('不能返回promise实例自身')
}
if (x instanceof myPromise) {
x.then(resolve, reject)
} else {
resolve(x);
}
} catch (err) {
reject(err);
}
}
if (state === pedding) {
this.onFulfills.push(fulfillFun);
this.onRejects.push(rejectFun);
} else if (state === fulfilled) {
fulfillFun(value);
} else {
rejectFun(value);
}
})
}
}