还在用Promise.all处理上千个请求?小心你的系统崩溃!这才是真正的并发控制实战

作者:佚名 时间:2025-11-18 07:23

字号

解锁JavaScript异步编程:Promise并发控制实战

在现代前端开发中,异步操作无处不在。JavaScript的Promise极大地简化了异步编程,但当我们需要同时处理大量异步任务时,直接使用Promise.all可能会带来性能问题甚至导致系统崩溃。

为什么需要并发控制?

想象一下,你有一个包含1000个URL的数组,如果同时发起所有请求,可能会导致:

实现Promise并发池

下面是一个简单而强大的并发控制函数:

class PromisePool {
   
  constructor(maxConcurrent) {
   
    this.maxConcurrent = maxConcurrent
    this.currentCount = 0
    this.queue = []
  }
  add(task) {
   
    return new Promise((resolve, reject) => {
   
      this.queue.push({
    task, resolve, reject })
      this._run()
    })
  }
  _run() {
   
    while (this.queue.length > 0 && this.currentCount < this.maxConcurrent) {
   
      const {
    task, resolve, reject } = this.queue.shift()
      this.currentCount++
      task()
        .then(resolve)
        .catch(reject)
        .finally(() => {
   
          this.currentCount--
          this._run()
        })
    }
  }
}

使用示例

// 创建最多同时处理3个请求的池
const pool = new PromisePool(3)
// 模拟异步任务
const tasks = Array.from({
    length: 10 }, (_, i) => 
  () => fetch(`/api/data/${
     i}`)
)
// 添加所有任务到池中
tasks.forEach(task => {
   
  pool.add(task).then(data => {
   
    console.log('任务完成:', data)
  })
})

总结

通过实现Promise并发控制,我们能够在保证系统稳定性的前提下,最大限度地利用可用资源。这种模式特别适用于文件上传、批量数据获取等场景,是每个前端开发者都应该掌握的实用技巧。

记住,好的并发控制就像交通信号灯,不是限制通行,而是确保所有车辆都能高效安全地到达目的地。

在现代前端开发中,异步操作无处不在。JavaScript的Promise极大地简化了异步编程,但当我们需要同时处理大量异步任务时,直接使用Promise.all可能会带来性能问题甚至导致系统崩溃。

为什么需要并发控制?

想象一下,你有一个包含1000个URL的数组,如果同时发起所有请求,可能会导致:

实现Promise并发池

下面是一个简单而强大的并发控制函数:

class PromisePool {
   
  constructor(maxConcurrent) {
   
    this.maxConcurrent = maxConcurrent
    this.currentCount = 0
    this.queue = []
  }
  add(task) {
   
    return new Promise((resolve, reject) => {
   
      this.queue.push({
    task, resolve, reject })
      this._run()
    })
  }
  _run() {
   
    while (this.queue.length > 0 && this.currentCount < this.maxConcurrent) {
   
      const {
    task, resolve, reject } = this.queue.shift()
      this.currentCount++
      task()
        .then(resolve)
        .catch(reject)
        .finally(() => {
   
          this.currentCount--
          this._run()
        })
    }
  }
}

使用示例

// 创建最多同时处理3个请求的池
const pool = new PromisePool(3)
// 模拟异步任务
const tasks = Array.from({
    length: 10 }, (_, i) => 
  () => fetch(`/api/data/${
     i}`)
)
// 添加所有任务到池中
tasks.forEach(task => {
   
  pool.add(task).then(data => {
   
    console.log('任务完成:', data)
  })
})

总结

通过实现Promise并发控制,我们能够在保证系统稳定性的前提下,最大限度地利用可用资源。这种模式特别适用于文件上传、批量数据获取等场景,是每个前端开发者都应该掌握的实用技巧。

记住,好的并发控制就像交通信号灯,不是限制通行,而是确保所有车辆都能高效安全地到达目的地。

责任编辑:CQITer新闻报料:400-888-8888   本站原创,未经授权不得转载
继续阅读
热新闻
推荐
关于我们联系我们免责声明隐私政策 友情链接