当前位置:首页 > JavaScript

js 实现一个任务队列

2026-03-02 01:21:59JavaScript

实现任务队列的基本思路

任务队列的核心是管理异步任务的顺序执行,通常需要支持任务添加、执行控制(如并发限制)、错误处理等功能。以下是几种常见实现方式:

基础版:顺序执行异步任务

创建一个队列数组,逐个执行任务,前一个任务完成后再执行下一个:

js 实现一个任务队列

class TaskQueue {
  constructor() {
    this.queue = [];
    this.isRunning = false;
  }

  addTask(task) {
    this.queue.push(task);
    if (!this.isRunning) this.run();
  }

  async run() {
    this.isRunning = true;
    while (this.queue.length > 0) {
      const task = this.queue.shift();
      try {
        await task();
      } catch (error) {
        console.error('Task failed:', error);
      }
    }
    this.isRunning = false;
  }
}

// 使用示例
const queue = new TaskQueue();
queue.addTask(() => new Promise(resolve => setTimeout(() => { console.log('Task 1'); resolve(); }, 1000)));
queue.addTask(() => new Promise(resolve => setTimeout(() => { console.log('Task 2'); resolve(); }, 500)));

进阶版:控制并发数

限制同时执行的任务数量,避免资源过载:

js 实现一个任务队列

class ConcurrentQueue {
  constructor(concurrency = 1) {
    this.queue = [];
    this.concurrency = concurrency;
    this.running = 0;
  }

  addTask(task) {
    this.queue.push(task);
    this.next();
  }

  next() {
    while (this.running < this.concurrency && this.queue.length) {
      const task = this.queue.shift();
      this.running++;
      task().finally(() => {
        this.running--;
        this.next();
      });
    }
  }
}

// 使用示例(并发数为2)
const queue = new ConcurrentQueue(2);
for (let i = 1; i <= 5; i++) {
  queue.addTask(() => new Promise(resolve => 
    setTimeout(() => { console.log(`Task ${i}`); resolve(); }, 1000)
  ));
}

功能增强版:支持优先级

通过优先级字段调整任务执行顺序:

class PriorityQueue {
  constructor() {
    this.queue = [];
  }

  addTask(task, priority = 0) {
    this.queue.push({ task, priority });
    this.queue.sort((a, b) => b.priority - a.priority);
  }

  async run() {
    while (this.queue.length > 0) {
      const { task } = this.queue.shift();
      try {
        await task();
      } catch (error) {
        console.error('Task failed:', error);
      }
    }
  }
}

// 使用示例
const queue = new PriorityQueue();
queue.addTask(() => console.log('Low priority'), 1);
queue.addTask(() => console.log('High priority'), 3);
queue.run();

错误处理与重试

为任务添加自动重试机制:

class RetryQueue {
  constructor(maxRetries = 3) {
    this.queue = [];
    this.maxRetries = maxRetries;
  }

  addTask(task) {
    this.queue.push(task);
  }

  async run() {
    for (const task of this.queue) {
      let retries = 0;
      while (retries <= this.maxRetries) {
        try {
          await task();
          break;
        } catch (error) {
          retries++;
          if (retries > this.maxRetries) console.error('Max retries reached:', error);
        }
      }
    }
  }
}

应用场景建议

  • 顺序执行:适合依赖前序结果的场景(如API串行调用)。
  • 并发控制:适用于资源密集型操作(如文件上传)。
  • 优先级队列:需要处理高优先级任务的场景(如用户交互响应)。
  • 重试机制:网络请求等可能临时失败的操作。

根据实际需求选择或组合上述方案。

标签: 队列任务
分享给朋友:

相关文章

php队列的实现

php队列的实现

PHP队列的实现方式 PHP中实现队列功能可以通过多种方式,根据需求选择适合的方案: 使用数组实现基础队列 PHP数组本身支持队列操作,利用array_push和array_shift函数:…

vue任务表单实现指南

vue任务表单实现指南

Vue 任务表单实现方法 表单基础结构 使用 Vue 的 v-model 实现数据双向绑定,创建任务表单的基础结构: <template> <form @submit.pre…

php 实现定时任务

php 实现定时任务

PHP 实现定时任务的方法 PHP 本身是脚本语言,通常需要借助外部工具或框架来实现定时任务。以下是几种常见的实现方式: 使用 Cron 任务 Cron 是 Linux 系统的定时任务工具,可以定期…

php实现redis消息队列

php实现redis消息队列

安装 Redis 扩展 确保 PHP 已安装 Redis 扩展。可以通过以下命令安装: pecl install redis 在 php.ini 中添加 extension=redis.so 并重…

php redis实现消息队列

php redis实现消息队列

使用 PHP 和 Redis 实现消息队列 Redis 是一个高性能的键值存储系统,支持多种数据结构,如列表(List)、发布/订阅(Pub/Sub)等,非常适合实现消息队列。以下是几种常见的实现方式…

php数组实现队列

php数组实现队列

使用数组实现队列的基本方法 在PHP中,数组可以模拟队列的先进先出(FIFO)特性。通过内置的数组函数,可以轻松实现队列的基本操作。 初始化队列 $queue = []; 入队操作(enque…