目录
promise
class MyPromise2 {
constructor(executor) {
// 规定状态
this.state = "pending";
// 保存 `resolve(res)` 的res值
this.value = undefined;
// 保存 `reject(err)` 的err值
this.reason = undefined;
// 成功存放的数组
this.successCB = [];
// 失败存放的数组
this.failCB = [];
let resolve = (value) => {
if (this.state === "pending") {
this.state = "fulfilled";
this.value = value;
this.successCB.forEach((f) => f());
}
};
let reject = (reason) => {
if (this.state === "pending") {
this.state = "rejected";
this.reason = reason;
this.failCB.forEach((f) => f());
}
};
try {
// 执行
executor(resolve, reject);
} catch (error) {
// 若出错,直接调用reject
reject(error);
}
}
then(onFulfilled, onRejected) {
if (this.state === "fulfilled") {
onFulfilled(this.value);
}
if (this.state === "rejected") {
onRejected(this.reason);
}
if (this.state === "pending") {
this.successCB.push(() => {
onFulfilled(this.value);
});
this.failCB.push(() => {
onRejected(this.reason);
});
}
}
}
promise.all()
- 简单说只有都成功才返回成功的数组,只要有一个失败就报错
Promise.all = function (promises) {
let result = [];
let count = 0;
function resolves(i, res) {
result[i] = res;
count++;
if (count == promises.length) {
resolve(result);
}
}
return new Promise((resolve, reject) => {
for (let i = 0; i < promises.length; i++) {
promises[i].then(
(res) => {
resolves(i, res);
},
(err) => {
reject(err);
}
);
}
});
};
promise.race()
- Promise.race() 同样返回一个合成的 Promise 实例,其会返回这一组中最先解决(fulfilled)或拒绝(rejected)的 Promise 实例的返回值
Promise.MyRace = function (promises) {
return new Promise((resolve, reject) => {
//遍历promises,获取每个promise的结果
promises.forEach((item, index) => {
Promise.resolve(item).then(
(res) => {
resolve(res);
},
(err) => {
reject(err);
}
);
});
});
};
promise.any()
- Promise.any() 相当于 Promise.all() 的反向操作,同样返回一个合成的 Promise 实例,都报错了返回都报错的集合。
Promise.any = function (promises) {
return new Promise((resolve, reject) => {
let count = 0;
let errResult = [];
if (promises.length == 0) {
resolve([]);
}
for (let item of promises) {
Promise.resolve(item).then(
(res) => {
resolve(res);
},
(err) => {
errResult[count++] = err;
if (count == promises.length) {
reject(errResult);
}
}
);
}
});
};