-
Notifications
You must be signed in to change notification settings - Fork 0
/
32、并发请求.js
37 lines (36 loc) · 999 Bytes
/
32、并发请求.js
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
function concurRequest(urls, maxNum) {
return new Promise((resolve) => {
if (urls.length === 0) {
resolve([]);
}
const results = [];
let indes = 0;
let counts = 0;
// 发送请求
async function request() {
if (indes === maxNum) {
return;
}
const i = indes;
const url = urls[indes];
indes++;
try {
const resp = await fetch(url);
results[i] = resp;
} catch (error) {
results[i] = error;
} finally {
counts++;
if (counts === urls.length) {
console.log('over');
resolve(results);
}
request();
}
}
const times = Math.max(maxNum, urls.length);
for (let index = 0; index < times; index++) {
request();
}
})
}