废话不多说,直接上代码:
class myPromise {
constructor(fn) {
this.status = 'pending';
this.resolveCbs = [];
this.rejectCbs = [];
this.value = null;
fn(this.resolve.bind(this), this.reject.bind(this))
}
resolve(val) {
this.value = val;
this.status = 'resolved';
this.resolveCbs.forEach(cb => {
cb(this.value);
})
}
reject(err) {
this.value = err;
this.status = 'rejected';
this.rejectCbs.forEach(cb => {
cb(this.value);
})
}
then(resolveCb, rejectCb) {
if (this.status === 'resolved') {
resolveCb(this.value);
} else if (this.status === 'rejected') {
rejectCb(this.value);
} else {
if (typeof resolveCb === 'function') {
this.resolveCbs.push(resolveCb)
}
if (typeof resolveCb === 'function') {
this.rejectCbs.push(resolveCb)
}
}
}
}
new myPromise((resolve, reject) => {
setTimeout(() => {
resolve(456)
}, 1000);
}).then(res => {
console.log(res)
})
这个简版的Promise只能实现一层then,不能做链式。