|
|
import type { Callback } from './index' |
|
|
export type Task = (cb: Callback) => void |
|
|
export type SyncTask = () => void |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export class TaskQueue { |
|
|
private tasks: Task[] = [] |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
readonly stopOnError: boolean = true |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
add (task: Task): void { |
|
|
this.tasks.push(task) |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
addSync (task: SyncTask): void { |
|
|
this.add((cb) => { |
|
|
try { |
|
|
task() |
|
|
cb() |
|
|
} catch (err: any) { |
|
|
cb(err) |
|
|
} |
|
|
}) |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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() |
|
|
} |
|
|
} |
|
|
|