Skip to content

Instantly share code, notes, and snippets.

@TwitchBronBron
Created August 31, 2022 14:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TwitchBronBron/6e4eed6f3c1f3190792a6347532e2bbc to your computer and use it in GitHub Desktop.
Save TwitchBronBron/6e4eed6f3c1f3190792a6347532e2bbc to your computer and use it in GitHub Desktop.
A typescript queue that runs async actions one at a time
/**
* Run one action at a time. Will run until all pending actions are complete.
*/
export class ActionQueue {
private queueItems: Array<{
action: () => Promise<any>;
resolve: (value: any) => void;
reject: (error: any) => void;
promise: Promise<any>;
}> = [];
public async run<T>(action: () => Promise<T>) {
const item = {
action: action,
resolve: null,
reject: null,
promise: new Promise((resolve, reject) => {
item.resolve = resolve;
item.reject = reject;
})
};
this.queueItems.push(item);
void this._runActions();
await item.promise;
}
private isProcessing = false;
private async _runActions() {
if (!this.isProcessing) {
this.isProcessing = true;
while (this.queueItems.length > 0) {
const queueItem = this.queueItems.shift();
try {
const result = await queueItem.action();
queueItem.resolve(result);
} catch (error) {
queueItem.reject(error);
}
}
this.isProcessing = false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment