不使用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
相关产品推荐
相关产品推荐

