Created
August 31, 2022 14:47
-
-
Save TwitchBronBron/6e4eed6f3c1f3190792a6347532e2bbc to your computer and use it in GitHub Desktop.
A typescript queue that runs async actions one at a time
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
/** | |
* 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