promiseQueue.js:
/*
* @Author: Simoon.jia
* @Date: 2024-09-04 16:00:24
* @LastEditors: Simoon.jia
* @LastEditTime: 2024-09-04 16:55:48
* @Description: 描述
*/
export class PromiseQueue {
constructor() {
this.queue = [];
this.isProcessing = false; // 标志当前是否有任务在执行
}
// 添加任务到队列
add(task) {
return new Promise((resolve, reject) => {
this.queue.push({ task, resolve, reject });
// console.log(this.queue, '执行队列');
this.runNext(); // 尝试运行下一个任务
});
}
// 运行下一个任务
runNext() {
if (this.isProcessing || this.queue.length === 0) {
return;
}
this.isProcessing = true;
const { task, resolve, reject } = this.queue.shift(); // 取出队首任务
task()
.then((result) => {
this.isProcessing = false;
resolve(result);
this.runNext(); // 任务完成后运行下一个任务
})
.catch((error) => {
this.isProcessing = false;
reject(error);
this.runNext(); // 处理失败后仍然运行下一个任务
});
}
}
调用:
useEffect(() => {
promiseQueue.current = new PromiseQueue();
}, []);
//动态添加任务
promiseQueue.current.add(() => new Promise((resolve, reject) => {
switch (voiceBroadcast) {
case '1':
audio.play();
audio.onended = () => {
resolve();
};
break;
case '2':
window.speechSynthesis.speak(sound);
sound.onend = () => {
resolve();
};
break;
default:
audio.play();
audio.onended = () => {
window.speechSynthesis.speak(sound);
sound.onend = () => {
resolve();
};
};
break;
// 添加播放结束后的回调函数
// audio.addEventListener('ended', onAudioEnded);
}
});
);
样例:
class PromiseQueue {
constructor() {
this.queue = [];
this.isProcessing = false; // 标志当前是否有任务在执行
}
// 添加任务到队列
add(task) {
return new Promise((resolve, reject) => {
this.queue.push({ task, resolve, reject });
this.runNext(); // 尝试运行下一个任务
});
}
// 运行下一个任务
runNext() {
if (this.isProcessing || this.queue.length === 0) {
return;
}
this.isProcessing = true;
const { task, resolve, reject } = this.queue.shift(); // 取出队首任务
task()
.then((result) => {
this.isProcessing = false;
resolve(result);
this.runNext(); // 任务完成后运行下一个任务
})
.catch((error) => {
this.isProcessing = false;
reject(error);
this.runNext(); // 处理失败后仍然运行下一个任务
});
}
}
// 示例任务函数,返回一个Promise
const createTask = (taskName, duration) => () => {
return new Promise((resolve) => {
setTimeout(() => {
console.log(`${taskName} completed`);
resolve(taskName);
}, duration);
});
};
// 使用PromiseQueue
const queue = new PromiseQueue();
queue.add(createTask('Task 1', 1000));
queue.add(createTask('Task 2', 500));
queue.add(createTask('Task 3', 1500));
// 动态添加任务
setTimeout(() => {
queue.add(createTask('Task 4', 1000));
}, 2000);
标签:resolve,队列,删减,queue,任务,promise,isProcessing,reject,runNext From: https://www.cnblogs.com/Simoon/p/18396885