Below, I have written a function that takes an array and a key to search and count the number of times the key matches an element in an array (in parallel). I am attempting to modify my function to count the number of matches asynchronously but don't know how to best go about it. Any insight or examples would be greatly appreciated.
My Code:
function countMatches(arr, key, done)
{
const threads = 4;
const pool = new StaticPool({
size: threads,
task: function (a)
{
let m = 0;
for (let i = 0; i < a.length; i++) {
if (a[i] == this.workerData) m++;
}
return m;
},
workerData: key
});
const size = arr.length / threads;
let res = 0, finished = 0;
for (let i = 0; i < threads; i++)
{
(async () =>
{
let r = await pool.exec(arr.slice(i * size, (i + 1) * size));
console.log("Result: " + r);
res += r;
finished++;
if (finished == threads)
{
done(res);
pool.destroy();
}
})();
}
}