File size: 817 Bytes
4d70170
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
export interface Job {
  id: string
  fn: () => Promise<void>
}

export class JobQueue {
  jobs: Job[] = []
  currentJob: Job

  queue(id: string, fn: Job['fn']) {
    const job: Job = {
      id,
      fn,
    }

    return new Promise<void>((resolve) => {
      const onDone = () => {
        this.currentJob = null
        const nextJob = this.jobs.shift()
        if (nextJob) {
          nextJob.fn()
        }
        resolve()
      }

      const run = () => {
        this.currentJob = job
        return job.fn().then(onDone).catch((e) => {
          console.error(`Job ${job.id} failed:`)
          console.error(e)
        })
      }

      if (this.currentJob) {
        this.jobs.push({
          id: job.id,
          fn: () => run(),
        })
      }
      else {
        run()
      }
    })
  }
}