源代码:
// 实现一个promise.all()
function promiseAll(array) {
return new Promise((resolve, reject) => {
if (!(array instanceof Array)) {
reject(new Error("params is not a valid array"));
}
let resultArr = new Array(array.length),
count = 0;
for (let i = 0; i < array.length; i++) {
Promise.resolve(array[i])
.then((res) => {
count++;
resultArr[i] = res;
if (count === array.length) resolve(resultArr);
})
.catch((error) => reject(error));
}
});
}
// 定义一个promise的生成器
const promiseGenerator = (num) =>
new Array(num).fill(0).map(
(_, index) =>
//如果没有用到item可以写成_
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(index);
}, Math.random() * 1000);
})
);
const proAll = promiseGenerator(10);
promiseAll(proAll).then(console.log);
案例结果图:
知识点扩展: