手撕promise
2020年8月7日
promise
// 手写promise
function myPromise(fn) {
let self = this;
self.status = 'pending';
self.value = undefined;
self.reason = undefined;
function resolve(value) {
if (self.status === 'pending') {
self.value = value;
self.status = 'resolved';
}
}
function reject(reason) {
if (self.status === 'pending') {
self.reason = reason;
self.status = 'rejected';
}
}
try {
fn(resolve, reject)
} catch (e) {
reject(e);
}
myPromise.prototype.then = (resolve, reject)=> {
switch (self.status) {
case 'resolved':
return resolve?resolve(self.value):null;
break;
case 'rejected':
return reject?reject(self.reason):null;
break;
default:
break;
}
}
myPromise.prototype.catch = reject=> {
return myPromise.prototype.then(null, reject);
};
}
let test = new myPromise((resolve,reject)=>{
// resolve(8888);
reject(4444)
})
test.then(res => {
console.log('res',res)
},err=>{
console.log('err',err)
})
test.catch(err=>{
console.log('err',err)
})