class WorkQueue<T> {
private lastJob: Promise<T> | undefined
async queueWork(work: () => Promise<T>): Promise<T> {
const nextJob = this.lastJob = this.lastJob?.then(work, _ => {}) ?? work()
try {
return await nextJob
} finally {
// ensure previous results can be garbage collected
if (nextJob === this.lastJob) { this.lastJob = undefined }
}
}
}
Okay maybe you should use a few more lines to be clearer but I like how neat this is.
Top comments (2)
do yo even need the array? make it just a promise and you don't need a condition.
ai decided to ignore errors from the previous tasks, because they get handled by the user of this class. and they only care about their own task.
what do you think?
You're right I don't! Actually I just came back here to edit the post for that, which is when I saw your reply. I had to change things a little bit to ensure the results from the previous promise chains can be garbage collected after the queue is emptied.
One issue with your solution there is that all errors will be returned as resolutions and it also needs to account for
this.lastJob
not being present (it still has array type in what you posted).