问题描述
我有下面的代码,如果传递的数组长度太高,并且处理每个数组元素要花费一秒钟的时间,那么如何在以下条件下使用工作线程?
function processData(arr){
var result = [];
for(var i = 0; i < arr.length; i++){
result.push(process(arr[i]));
}
return result;
}
function process() {
// some code here takes 1 second to execute
}
processData(arr);
解决方法
您可以使用workerpool
npm软件包在工作线程中完成长时间的处理工作,诸如此类
const workerpool = require('workerpool');
const pool = workerpool.pool();
const arr = [...] // Large Data set which is to be processed
new Promise((resolve,reject) => {
pool.exec(
arr => {
var result = [];
for(var i = 0; i < arr.length; i++){
/*
Do the long processing on data
*/
const processedData = a[i];
result.push(processedData);
}
return result;
},[arr]
)
.then(result => resolve(result))
.catch(err => reject(err));
});