You need to enable JavaScript to run this app. 不使用Promise如何编写实现并行计算的paralell函数?
优惠活动
大模型
产品
解决方案
定价
更多

不使用Promise如何编写实现并行计算的paralell函数?

不使用Promise实现并行计算函数

核心实现思路

  • 先定义和任务数量长度一致的结果数组,保证最终结果的顺序和传入的任务顺序一一对应
  • 设置完成计数变量,每执行完一个任务就更新计数并存储对应位置的结果
  • 当完成计数等于总任务数时,触发最终回调返回完整结果数组

同步任务版本实现(匹配你给出的示例)

你给出的示例中所有任务都是同步执行的,实现代码如下:

function parallel(tasks, callback) {
  const total = tasks.length
  const result = new Array(total)
  let finishCount = 0

  for (let index = 0; index < total; index++) {
    const [fn, args = []] = tasks[index]
    result[index] = fn(...args)
    finishCount++
    if (finishCount === total) {
      callback(result)
    }
  }
}

// 测试用例
const first = function(a, b) {
  return a + b
}
const second = function() {
  return false;
}
parallel([[first, [3, 4]], [second]], function(res) {
    console.log(res); // 输出 [7, false]
});

注:你示例中写的函数名为paralell属于拼写误差,上述实现用了标准拼写parallel,可根据需要自行调整函数名。

支持异步任务的拓展版本

如果需要支持异步任务并行执行,可调整实现让任务通过注入的回调上报结果:

function parallel(tasks, callback) {
  const total = tasks.length
  const result = new Array(total)
  let finishCount = 0

  for (let index = 0; index < total; index++) {
    const [fn, args = []] = tasks[index]
    // 给每个任务传入done回调接收异步返回结果
    fn(...args, (res) => {
      result[index] = res
      finishCount++
      if (finishCount === total) {
        callback(result)
      }
    })
  }
}

// 异步任务测试用例
const asyncFirst = (a, b, done) => setTimeout(() => done(a + b), 1000)
const asyncSecond = (done) => setTimeout(() => done(false), 500)
parallel([[asyncFirst, [3, 4]], [asyncSecond]], function(res) {
  console.log(res); // 1秒后输出 [7, false]
})

内容的提问来源于stack exchange,提问作者argentonik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 01:51:04