简单实现手写js中的promise
class MyPromise {
constructor(fn) {
this.state = "pending";
this.value = null;
this.resolve = this.resolve.bind(this);
this.reject = this.reject.bind(this);
this.resolveStack = [];
this.rejectStack = [];
// 创建时立马执行
fn(this.resolve, this.reject);
}
static all(li) {
return new MyPromise((rs, rj) => {
if (!Array.isArray(li)) {
return rj("not array");
}
const results = [];
let completes = 0;
li.forEach((_promise, idx) => {
_promise.then((res) => {
results[idx] = res;
completes++;
if (completes === li.length) {
rs(results);
}
});
});
});
}
resolve(value) {
this.value = value;
this.state = "fulfilled";
while (this.resolveStack.length) {
this.value = this.resolveStack.shift()(this.value);
}
}
reject(value) {
this.state = "rejected";
this.value = value;
}
then(onFulfilled, onRejected) {
this.resolveStack.push(onFulfilled);
this.rejectStack.push(onRejected);
return this;
}
}
测试一下试试
new MyPromise((rs, rj) => {
setTimeout(() => {
rs(1);
}, 1000);
})
.then((val) => {
console.log("running ", val);
return val + 1;
})
.then((val) => {
console.log("running ", val);
return val + 1;
});
const returnPro = (num) => {
return new MyPromise((rs, rj) => {
setTimeout(() => {
console.log("returnPro running", num);
rs(num);
}, 1000 * num);
});
};
MyPromise.all([returnPro(1), returnPro(2), returnPro(3)]).then((res) => {
console.log(res);
});
结果问题不大