0%

如何封装一个有最大请求限制的方法

核心的话,就是当请求已经达到最高并发量的时候将后续的请求放到请求队列中

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
47
48
49
50
51
52
53
54
55
56

// 等待队列
const request_queue: (() => void)[] = [];
// 最大请求并发限制
const max_request_count = 5;
let current_request_count = 0;

// 模拟后端接口返回时间
function get(api: string, params: object) {
console.log('请求中')
return new Promise((resolve) => {
setTimeout(() => {
resolve({ data: api, params });
}, 1000+Math.random() * 3000 );
});
}

function handleRes(resolve: Function, data: any) {
current_request_count--;
if (request_queue.length > 0) {
const next = request_queue.shift();
next?.();
}
resolve(data);
}
function request(api: string, params: object) {
return new Promise((resolve) => {
if (current_request_count > max_request_count) {
// await
new Promise<void>((continue_request) => {
// 已达到最大请求数,等待中
request_queue.push(continue_request);
}).then(() => {
get(api, params).then((data) => {
handleRes(resolve, data);
});
});
return;
}
current_request_count++;
get(api, params).then((data) => {
handleRes(resolve, data);
});
});
}

function test() {
let i = 0;
while (i++ < 20) {
let j = i
request('/api/test', { i }).then((data) => {
console.log(`第${j}次请求完成`, `还有${request_queue.length}个等待任务`);
});
}
}
test()