promise的实现原理
function myPromise(fn) {
this.cbs = [];
const resolve = (value) => {
setTimeout(() => {
this.data = value;
this.cbs.forEach((cb) => cb(value));
})
}
fn(resolve);
}
myPromise.prototype.then = function (onResolved) {
return new myPromise((resolve) => {
this.cbs.push(() => {
const res = onResolved(this.data);
if (res instanceof myPromise) {
res.then(resolve);
} else {
resolve(res);
}
});
});
}
let a = new myPromise(function (resolve) {
setTimeout(function () {
resolve('123')
}, 1000)
})
a.then((e) => {
console.log(e)
})