Hello everybody,
I’m trying to write some IO-intensive code, and I need to optimize it by using parallel computation.
I want to mix async and sync code, so several synchronous function are launched in parallel within the same thread.
export class ExpensiveObject {
updateObject() {
for (item in this._items) {
// even though syncupdate performs
// synchronously, the for ... in
// loop makes several calls
// to the function run in parallel
// within the same thread
syncUpdate(this._items[item], this._items[item].length );
}
// now how can I run this code AFTER all updates are done?
console.log(
'after update'
);
}
}
// This is a recursive function that updates all elements in in the
// items array.
// Recursivity guarantee that updates are done synchronously
async function syncUpdate(items, index) {
if (index === 0) {
return;
}
await items[index-1].update();
return syncUpdate(items, index-1);
}
I can fix it by awiting for syncUpdate:
await syncUpdate(this._items[item], this._items[item].length );
but this way I loose parallel execution.
How can I wait for all the syncUpdates functions to finish? Can I do this with plain JS without using a package?
If no, is there any NPM package that could help me?