refactor AsyncQueue

This commit is contained in:
linyuchen
2024-05-01 16:03:53 +08:00
parent 84aa4ef9e2
commit 7484ef4f88
5 changed files with 55 additions and 52 deletions

View File

@@ -0,0 +1,33 @@
import { sleep } from '@/common/utils/helper';
type AsyncQueueTask = (() => void) | Promise<void> ;
export class AsyncQueue {
private tasks: (AsyncQueueTask)[] = [];
public addTask(task: AsyncQueueTask) {
this.tasks.push(task);
if (this.tasks.length === 1) {
this.runQueue().then().catch(()=>{});
}
}
private async runQueue() {
while (this.tasks.length > 0) {
const task = this.tasks[0];
try {
if (task instanceof Promise) {
await task;
}
else{
task();
}
} catch (e) {
console.error(e);
}
this.tasks.shift();
await sleep(100);
}
}
}

View File

@@ -1,37 +0,0 @@
import { randomUUID } from "crypto";
class AsyncQueue {
private tasks: Map<string, any> = new Map<string, any>();
private MainQuene: any = undefined;
private callbacks: Map<string, any> = new Map<string, any>();
private ArgList: Map<string, any> = new Map<string, any>();
private busy = false;
// 添加任务到队列中 返回任务ID
public async addTask(task: any, args: any[], callBack: any) {
let uuid = randomUUID();
this.tasks.set(uuid, task);
this.callbacks.set(uuid, callBack);
this.ArgList.set(uuid, args);
return uuid;
}
public async runQueue() {
if (!this.MainQuene) {
this.MainQuene = this.Quene();
}
await this.MainQuene;
this.MainQuene = undefined;
}
public async Quene() {
for (let [uuid, task] of this.tasks) {
//console.log(uuid,...this.ArgList.get(uuid));
let result = await task(...this.ArgList.get(uuid));
console.log(result);
let cb = this.callbacks.get(uuid);
cb(result);
this.tasks.delete(uuid);
this.ArgList.delete(uuid);
this.callbacks.delete(uuid);
}
}
}
export const ImageQuene = new AsyncQueue();