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.