javascript异步队列顺序消费的核心是控制执行时序而非队列结构,通过promise链或async/await串行化任务流,确保前一个任务完成后再执行下一个。

JavaScript 中异步队列按顺序消费任务,核心是**避免并发执行、确保前一个任务完成后再启动下一个**。这不靠“队列数据结构”本身实现,而靠控制执行逻辑——用 Promise 链或 async/await 串行化任务流。
用 async/await 串行执行队列任务
把任务存成函数数组,遍历并 await 每个调用,自然形成串行链:
const queue = [
() => delay(1000).then(() => console.log('task 1')),
() => delay(500).then(() => console.log('task 2')),
() => delay(800).then(() => console.log('task 3'))
];
async function runQueue() {
for (const task of queue) {
await task(); // 等前一个完成,再执行下一个
}
}
runQueue();
✅ 关键点:每个 task() 返回 Promise,await 保证阻塞式等待;循环不会“跳过”或“并发”执行。
封装可复用的顺序执行器
把逻辑抽成通用函数,支持任意异步函数数组:
Java Maven 项目审查工作流的通用输入处理。当 Java Maven 项目以 ZIP压缩包或 GitLab 仓库 URL 形式提供且需要...时使用。
- 接收任务数组(每个元素是返回 Promise 的函数)
- 逐个调用并 await,错误可 catch 或抛出
- 支持传参、返回结果数组(可选)
async function serialRun(tasks) {
const results = [];
for (const task of tasks) {
try {
const res = await task();
results.push(res);
} catch (err) {
console.error('Task failed:', err);
throw err; // 或 continue,按需决定失败策略
}
}
return results;
}
// 使用示例
serialRun([
() => fetch('/api/a').then(r => r.json()),
() => fetch('/api/b').then(r => r.json()),
() => fetch('/api/c').then(r => r.json())
]).then(console.log);
用 reduce 构建 Promise 链(函数式写法)
利用 Array.prototype.reduce 累积 Promise,显式构造链式调用:
const queue = [task1, task2, task3];
queue.reduce((promiseChain, task) => {
return promiseChain.then(() => task());
}, Promise.resolve());
// 等价于:Promise.resolve().then(task1).then(task2).then(task3)
⚠️ 注意:这种方式不便于错误统一处理或收集结果,适合简单串行;若需中断或捕获中间错误,推荐用 for-await 或封装函数。
需要暂停/取消/动态加任务?用类封装队列
当需求变复杂(如暂停、取消、运行中追加任务),建议用 class 管理状态:
- 内部维护待执行任务队列和运行标志
- 每次只取一个任务执行,完成后自动取下一个
- 提供 push(task)、pause()、resume() 方法
class SerialQueue {
constructor() {
this.queue = [];
this.isRunning = false;
}
push(task) {
this.queue.push(task);
if (!this.isRunning) this.run();
}
async run() {
if (this.queue.length === 0) return;
this.isRunning = true;
while (this.queue.length > 0) {
const task = this.queue.shift();
await task();
}
this.isRunning = false;
}
}
const q = new SerialQueue();
q.push(() => delay(200).then(() => console.log('A')));
q.push(() => delay(300).then(() => console.log('B')));
不复杂但容易忽略:顺序消费的本质不是“存”,而是“控”。只要每个任务都等前一个 Promise settle 后再触发下一个,队列就自然有序。别被“队列”二字带偏去实现底层数据结构,重点在执行时序控制。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










