最简单的promise代码,没有之一
function promise(fn) {
this.cache = null;
const resolve = (value) => {
this.data = value;
this.cache(value);
};
fn(resolve);
}
promise.prototype.then = function (func_onResolved) {
this.cache = func_onResolved;
};`
//测试
new promise((resolve) => {
setTimeout(() => {
resolve(1);
}, 1500);
}).then((res) => {
console.log(res, "回调");
});
其实promise最核心的原理就是function的链式调用,如果明白这个,就很好理解了