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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| class TaskQueue { constructor(max = 3) { this.max = max this.runList = [] this.runLog = [] this.taskList = [] } addTask(task) { this.taskList.push(task) this.run() } getTaskList() { return this.taskList.map(i => ({ ...i, run: undefined })) } getRunList() { return this.runList } getRunLog() { return this.runLog } run() { const length = this.taskList.length if (!length) { return } const min = Math.min(this.max, length) for (let i = 0; i < min; i++) { this.max-- const task = this.taskList.shift() this.runList.push(Object.assign({}, task, { run: undefined, callback: undefined })) task.run().then(res => { task.callback && task.callback(true) this.runLog.push(Object.assign({ success: true }, task, { run: undefined, callback: undefined })) console.log(res) }).catch(err => { task.callback && task.callback(false) this.runLog.push(Object.assign({ success: false }, task, { run: undefined, callback: undefined })) console.log(err) }).finally(() => { this.max++ this.run() }) } } }
const taskQueue = new TaskQueue()
let i = 0
export function createTask(task) { const index = i++ const defaultInfo = { index, name: 'task', id: Date.now(), run: task } taskQueue.addTask(Object.assign({}, defaultInfo, task)) }
export function getTaskList() { return taskQueue.getTaskList() }
export function getRunList() { return taskQueue.getRunList() }
export function getRunLog() { return taskQueue.getRunLog() }
|