前端请求队列

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
57
58
59
60
61
62
63
64
65
66
67
import axios from 'axios';

interface Queue {
url: string;
method: string;
data: any;
resolve: Function;
reject: Function;
}

interface Header {
[key: string]: string;
}

class Request {
QUEUES: Queue[] = [];
CONCURRENCY_NUMBER: number;
TASKING_NUMBER: number = 0;

constructor(concurrencyNumber: number = 3, header: Header = {}) {
this.CONCURRENCY_NUMBER = concurrencyNumber;
this.HEADER = header;
}

setHeader(key: string = '', value: string = ''): void {
this.HEADER[key] = value;
}

push(url: string, method: string, data: any = null): Promise<any> {
return new Promise((resolve, reject): void => {
this.QUEUES.push({url, method, data, resolve, reject});
this.run();
})
}

private run(): void {
if (this.TASKING_NUMBER < this.CONCURRENCY_NUMBER) {
this.request();
}
}

private next(): void {
if (this.QUEUES.length > 0 && this.TASKING_NUMBER < this.CONCURRENCY_NUMBER) {
this.request();
}
}

private request() {
let task = this.QUEUES.shift();
this.TASKING_NUMBER++;

axios({
url: task!.url,
method: task!.method,
headers: this.HEADER,
data: task!.data,
withCredentials: true
}).then((response: any): void => {
task!.resolve(response);
}).catch((reason: any): void => {
task!.reject(reason);
}).finally((): void => {
this.TASKING_NUMBER--;
this.next();
});
}
}