任务队列的中断和恢复
作者:xie392地址:https://v.douyin.com/iexAbdge/更新时间:2024-12-21
案例代码
1/**2* 依次顺序执行一系列任务3* 所有任务全部完成后可以得到每个任务的执行的结果4* 需要返回两个方法,start 用于启动任务, pause 用于暂停任务5* 每个任务具有原子性,即不可中断,只能在两个任务之间中断6* @param {...Function} tasks 任务列表,每个任务无参、异步7*/8function processTasks(...tasks) {9// 任务队列10const tasksQueue = []11// 是否正在运行12let isRunning = false13// 当前执行任务索引14let currentIndex = 01516async function start() {17return new Promise((resolve, reject) => {18// 如果正在运行则直接返回19if (isRunning) return2021isRunning = true22// 启动任务23while (currentIndex < tasks.length) {24// 执行任务25tasksQueue.push(tasks[currentIndex++]())26if (!isRunning) break27}2829// 等待所有任务执行完毕30isRunning = false3132resolve(tasksQueue)33})34}3536function pause() {37isRunning = false38}3940return {41start,42pause43}44}4546const tasks = [47async () => {48console.log("task1 start");49await new Promise((resolve) => setTimeout(resolve, 2000));50console.log("task1 end");51return "task1 result";52},53async () => {54console.log("task2 start");55await new Promise((resolve) => setTimeout(resolve, 1000));56console.log("task2 end");57return "task2 result";58},59async () => {60console.log("task3 start");61await new Promise((resolve) => setTimeout(resolve, 3000));62console.log("task3 end");63return "task3 result";64},65];6667const { start, pause } = processTasks(...tasks);6869start().then((results) => {70console.log(results);71pause();72});
输出结果:
1task1 start2task2 start3task3 start4[ Promise { <pending> }, Promise { <pending> }, Promise { <pending> } ]5task2 end6task1 end7task3 end
目录