Skip to content

Instantly share code, notes, and snippets.

@DIY0R
Created August 23, 2024 15:37
Show Gist options
  • Save DIY0R/3f7de5ecd55331b385190348a15fa07d to your computer and use it in GitHub Desktop.
Save DIY0R/3f7de5ecd55331b385190348a15fa07d to your computer and use it in GitHub Desktop.
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