A sequential work queue for typescript in 11 lines of code

insidewhy - Feb 20 '23 - - Dev Community
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 }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Okay maybe you should use a few more lines to be clearer but I like how neat this is.

. . . . . . .
Terabox Video Player