可以并行执行js函数吗?

Possible to execute js function parallely?

function heavyCalculationTask(param) {}

for(let i = 0; i<5000;i++) {
  heavyCalculationTask(i)
}

我想知道我们是否可以在某种程度上并行执行 heavyCalculationTask,以充分利用我们在机器上拥有的内核数量,而不是让它一个接一个地循环?

一开始想着把heavyCalculationTask改成返回promise最后用Promise.all等待所有任务完成,但估计也无济于事,转了进入 Promise 只是改变了执行顺序,就花费的总持续时间而言,如果不是更差的话,仍然相似

另一个想法是将heavyCalculationTask移动到它自己的文件中并使用worker_thread来执行?但在开始之前,我想知道是否还有其他选择

Initially I thought of turning heavyCalculationTask into returning promise and eventually use Promise.all to wait for all the task to be completed, but guess it doesn't help, turning it into Promise just changing the order of execution...

正确,它仍然 运行ning 在同一个线程上。事实上,它甚至不会改变执行顺序;当您调用 new Promise 时,promise 执行器函数会同步 运行。 (它只是对您何时可以看到结果有轻微影响。)

Another idea is to move heavyCalculationTask into it's own file and using worker_thread...

是的,worker_threads is how you do it on Node.js. (On the web platform, the equivalent is web workers.) Each worker has its own thread, separate from the main thread, and so can do things truly in paralle withl each other and with the main thread (or not, depending on how the operating system schedules the threads). Another option on Node.js is to use full child processes,但如果您只需要一个单独的线程,工作线程是更简单的选择。