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 68 69 70 71 72
| import axios from 'axios';
interface Option { url: string; method?: string; param?: string; data?: string; }
interface Queue extends Option { resolve: Function; reject: Function; }
interface Header { [key: string]: string; }
class Request { queues: Queue[] = []; concurrencyNumber: number = 0; taskingNumber: number = 0; header: Header = {};
constructor(concurrencyNumber: number = 3, header: Header = {}) { this.concurrencyNumber = concurrencyNumber; this.header = header; } push(option: Option): Promise<any> { return new Promise((resolve, reject): void => { if (!option.method) { option.method = 'GET'; } this.queues.push({...option, resolve, reject}); this.run(); }) }
private run(): void { if (this.taskingNumber < this.concurrencyNumber) { this.request(); } }
private next(): void { if (this.queues.length > 0 && this.taskingNumber < this.concurrencyNumber) { this.request(); } }
private request() { let task = this.queues.shift(); this.taskingNumber++;
axios({ url: task!.url, method: task!.method, headers: this.header, params: task?.param, data: task?.data, withCredentials: true }).then((response: any): void => { task!.resolve(response); }).catch((reason: any): void => { task!.reject(reason); }).finally((): void => { this.taskingNumber--; this.next(); }); } }
|