class myPromise {
static PENDING = 'pending';
static FULFILLED = 'fulfilled';
static REJECTED = 'rejected';
constructor(callback) {
this.PromiseState = myPromise.PENDING;
this.PromiseResult = null;
this.result = null;
try {
callback(this.resolve.bind(this), this.reject.bind(this));
} catch(error) {
this.reject(error)
}
}
resolve(value) {
if(this.PromiseState === myPromise.PENDING){
this.PromiseState = myPromise.FULFILLED;
this.result = value;
}
}
reject(reason) {
if(this.PromiseState === myPromise.PENDING){
this.PromiseState = myPromise.REJECTED;
this.result = reason;
}
}
then(onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
onRejected = typeof onRejected === 'function' ? onRejected : reason => {
throw reason;
};
if(this.PromiseState === myPromise.FULFILLED) {
onFulfilled(this.result)
}
if(this.PromiseState === myPromise.REJECTED) {
onRejected(this.result)
}
}
catch() {
}
}
const result = new myPromise((req, rej) => {
throw new Error('白嫖不成功');
})
result.then((data) => {
console.log('myPromise then onFulfilled--->', data);
}, (err) => {
console.log('myPromise then onRejected--->', err);
})