{
function Promise(fn) {
this.cbs = []; //收集回调函数集
const resolve = (value) => {
setTimeout(() => {
this.data = value;
this.cbs.forEach((cb) => cb(value));//执行回调的函数
});
}
fn(resolve)
}
Promise.prototype.then = function (onResolved) {
console.log(onResolved)
return new Promise((resolve) => {
this.cbs.push(() => {
const res = onResolved(this.data);
if (res instanceof Promise) {
//resolve 向下执行
res.then(resolve)
} else {
//执行cbs函数
resolve(res) //执行回调函数
}
});
});
}
const fn = (resolve) => {
setTimeout(() => {
resolve(1);
}, 500);
};
new Promise(fn).then(res => {
console.log(res)
});
}
console