Repository navigation
Expand file tree
/
Copy pathAsyncParallelQueue.ts
More file actions
82 lines (74 loc) · 2.23 KB
/
Copy pathAsyncParallelQueue.ts
File metadata and controls
82 lines (74 loc) · 2.23 KB
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
73
74
75
76
77
78
79
80
81
82
/**
* 处理多任务并行队列处理
*/
export class AsyncParallelQueue {
currentRunningNum = 0;
maxRunningNum = 0;
taskID = 0;
tasks = [];
results = [];
complete:(rets:any[])=>void = null;
handler: (param: any) => Promise<any> = null;
/**
*
* @param maxParallelNum 最大的并行处理数量
*/
constructor(maxParallelNum: number = 1) {
this.maxRunningNum = maxParallelNum;
}
/**
* push 任务
* @param tasks 任务数组参数
* @param handler 任务调度函数,该函数需返回一个Promise
* @param complete 执行完成回调函数
*/
public pushTasks(tasks: any[], handler: (param: any) => Promise<any>, complete:(rets:any[])=>void ) {
this.tasks = tasks;
this.handler = handler;
this.complete = complete;
this._play();
}
/**
* push 任务
* @param tasks 任务数组参数
* @param handler 任务调度函数,该函数需返回一个Promise
* @returns tasks所有任务结束的Promise
*/
public pushTasksPromise(tasks: any[], handler: (param: any) => Promise<any> ):Promise< any[]> {
this.tasks = tasks;
this.handler = handler;
this._play();
return new Promise((resolve, reject) => {
this.complete = resolve;
} )
}
private _complete(){
let rets = [];
this.results.sort( (a,b)=>{
return a.id - b.id;
})
this.results.forEach( (a)=>{
rets.push(a.ret);
} )
this.complete && this.complete(rets);
}
private _play(){
if (this.currentRunningNum === 0 && this.tasks.length === 0){
this._complete();
return;
}
while( this.tasks.length >0 && this.currentRunningNum < this.maxRunningNum ){
this.currentRunningNum++;
let taskID = this.taskID++;
let dohandler = (res) => {
this.currentRunningNum--;
this.results.push({
id: taskID,
ret: res
});
this._play();
}
this.handler(this.tasks.shift()).then(dohandler, dohandler);
}
}
}