Created
August 23, 2024 15:37
-
-
Save DIY0R/3f7de5ecd55331b385190348a15fa07d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AsyncTaskQueue { | |
private tasks: (() => Promise<void>)[] = []; | |
private isRunning = false; | |
public addTask(task: () => Promise<void>, signal?: AbortSignal): Promise<void> { | |
return new Promise((resolve, reject) => { | |
const wrappedTask = async () => { | |
if (signal?.aborted) return reject(new Error('Task aborted')); | |
try { | |
await task(); | |
resolve(); | |
} catch (error) { | |
reject(error); | |
} | |
}; | |
this.tasks.push(wrappedTask); | |
this.runNext(); | |
}); | |
} | |
private async runNext() { | |
if (this.isRunning || this.tasks.length === 0) return; | |
this.isRunning = true; | |
const task = this.tasks.shift(); | |
await task(); | |
this.isRunning = false; | |
this.runNext(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment