class myPromise {
constructor(callback) {
this.callback = callback;
this.status = 'pendding';
this.result = null;
this.err = null;
this.resolveR = null;
this.rejectR = null;
this.resolve = val => {
this.status = 'resolve';
this.result = val;
this.resolveR && this.resolveR(val);
}
this.reject = err => {
this.status = 'reject';
this.err = err;
this.rejectR && this.rejectR(err);
}
this.callback(this.resolve, this.reject);
}
then(callback) {
this.status === 'resolve' ? callback(this.result) : this.resolveR = callback;
return new myPromise(this.callback);
}
catch(callback) {
this.status === 'reject' ? callback(this.err) : this.rejectR = callback;
return new myPromise(this.callback);
}
}
new myPromise((resolve, reject) => {
setTimeout(() => {
resolve(1);
}, 1000);
}).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
简单的总结,希望对大家有所帮助,如有不对的地方也烦请指出,谢谢!