49 lines
1.0 KiB
TypeScript
49 lines
1.0 KiB
TypeScript
export class MethodLocker<R> {
|
|
private isLocked: boolean = false;
|
|
private queue: Array<() => Promise<any>> = [];
|
|
|
|
/**
|
|
* 执行被锁定的方法
|
|
* @param task 需要执行的任务,返回一个 Promise
|
|
*/
|
|
async execute(task: () => Promise<R>): Promise<R> {
|
|
// 如果当前没有被锁定,直接执行任务
|
|
if (!this.isLocked) {
|
|
this.isLocked = true;
|
|
try {
|
|
return await task();
|
|
} finally {
|
|
this.isLocked = false;
|
|
await this.dequeue();
|
|
}
|
|
} else {
|
|
// 如果被锁定,将任务加入队列并等待
|
|
return new Promise<R>((resolve, reject) => {
|
|
this.queue.push(async () => {
|
|
try {
|
|
const result = await task();
|
|
resolve(result);
|
|
} catch (error) {
|
|
reject(error);
|
|
} finally {
|
|
this.dequeue();
|
|
}
|
|
});
|
|
});
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 处理队列中的下一个任务
|
|
*/
|
|
private dequeue(): Promise<R> | undefined {
|
|
if (this.queue.length > 0) {
|
|
const nextTask = this.queue.shift();
|
|
if (nextTask) {
|
|
return this.execute(nextTask);
|
|
}
|
|
}
|
|
return undefined;
|
|
}
|
|
}
|