DEV Community

insidewhy
insidewhy

Posted on

A sequential work queue for typescript in 11 lines of code

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.

Top comments (2)

Collapse
 
bias profile image
Tobias Nickel

do yo even need the array? make it just a promise and you don't need a condition.

class WorkQueue<T> {
  private lastJob: Promise<T> = []

  async queueWork(work: () => Promise<T>): Promise<T> {
      this.lastJob = lastJob
        .catch(_=>_)
        .then(work)
      return await this.lastJob;
  }
}
Enter fullscreen mode Exit fullscreen mode

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?

Collapse
 
insidewhy profile image
insidewhy • Edited

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).