Open theydy opened 5 years ago
简化版
function MiniPromise(fn) {
this.cbs = [];
this.value = '';
this.state = 'pending';
const resolve = (data) => {
setTimeout(() => {
this.state = 'resolved';
this.value = data;
this.cbs.map(cb => cb.onResolved(value));
}, 0);
}
fn(resolve);
}
MiniPromise.prototype.then = function (onResolved, onRejected) {
return new MiniPromise((resolve, reject) => {
this.cbs.push({
onResolved: (value) => {
const res = onResolved(value);
if (res instanceof MiniPromise) {
res.then(resolve);
} else {
resolve(res);
}
},
})
})
}