# 28.用Promise.all实现限制三个并发的网路请求
const limit = 3;
let count = 100;
// 网络请求
const images = Array.from({ length: 100 }, (_, i) => `Image ${i + 1}`);
const axios = function (url) {
return new Promise(function (resolve, reject) {
const randomNum = Math.floor(1000 * Math.random());
setTimeout(() => {
resolve(url + ` randomNum: ${randomNum}`);
}, randomNum);
});
};
// 结果列表
let resList = [];
// 当前并发数
let currRequestTimes = 0;
// 递归函数,按顺序上传图片
function uploadImagesInOrder() {
return new Promise(function (resolve, reject) {
if(images.length > 0){
const url = images.shift();
axios(url).then((res) => {
resList.push(res);
console.error('res', res);
if(images.length > 0){
uploadImagesInOrder();
}else{
resolve()
}
});
}else{
resolve();
}
})
}
let promiseList = [];
async function startUpload(){
// 并发
for (let i = 0; i < limit; i++) {
promiseList.push(uploadImagesInOrder());
}
const res = await Promise.all(promiseList);
console.log('end');
}
startUpload();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46