Promise.all解决了什么问题
对于多个并发请求,希望拿到所有的并发结果后,再进行数据的处理。传统解决方案是,比如通过嵌套回调函数解决。
ajax1((res1) => {
ajax2(res2 => {
ajax3(res3 => {
})
})
})
// 通过一个计数器统计是否拿到所有的结果
// 通过let声明的局部变量确保结果顺序
Promise.myAll = function (list) {
return new Promise(function (resolve, reject) {
const res = new Array(list.length);
let count = 0;
for (let i = 0; i < list.length; i++) {
const promise = list[i];
promise.then(function (value) {
res[i] = value;
count++;
if (count === list.length) {
resolve(res);
}
}, function (reason) {
reject(reason);
});
}
});
};