File size: 1,659 Bytes
36ba3ef |
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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
import type { Callback } from './index'
export type Task = (cb: Callback) => void
export type SyncTask = () => void
/**
* A simple utility class for queuing up a series of async tasks to execute.
*/
export class TaskQueue {
private tasks: Task[] = []
/**
* If true, the task list will stop executing if one of the tasks throws an error.
*/
readonly stopOnError: boolean = true
/**
* Adds a new async task to this queue. The provided callback should be executed when
* the async task is complete.
*
* @param task - The async task to add.
*/
add (task: Task): void {
this.tasks.push(task)
}
/**
* Adds a synchronous task toi this queue.
*
* @param task - The sync task to add.
*/
addSync (task: SyncTask): void {
this.add((cb) => {
try {
task()
cb()
} catch (err: any) {
cb(err)
}
})
}
/**
* Runs all tasks currently in this queue and empties the queue.
*
* @param cb - The optional callback to be executed when all tasks in this queue have
* finished executing.
*/
runAll (cb?: Callback): void {
const taskList = this.tasks
this.tasks = []
let index = -1
const runNext: () => void = () => {
index++
if (index >= taskList.length) {
if (cb !== undefined) cb()
return
}
try {
taskList[index]((err) => {
if (err !== undefined) {
if (cb !== undefined) cb(err)
if (this.stopOnError) return
}
runNext()
})
} catch (err: any) {
if (cb !== undefined) cb(err)
}
}
runNext()
}
}
|