# 实现 Promise.all
# Promise.all() 方法返回一个 promise,全部成功返回才返回一个数组结果,当有一个错误返回就直接返回错误结果
const t = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("success");
// reject("t");
}, 1000);
});
const h = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("success");
// reject("h");
}, 1000);
});
Promise.myAll = function (promises) {
return new Promise((resolve, reject) => {
if (!Array.isArray(promises)) return;
const result = [];
const len = promises.length;
for (let i = 0; i < len; i++) {
Promise.resolve(promises[i])
.then((r) => {
result[i] = r;
if (i === promises.length - 1) {
return resolve(result);
}
})
.catch((e) => {
reject(e);
});
}
});
};
Promise.myAll([t, h])
.then((r) => {
console.log(r, "r");
})
.catch((e) => {
console.log(e, "e");
});
//['success', 'success'] 'r'
← Promise Promise.race →