Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

True Parallelism in Node.js / Javascript?


const sleep = (ms) => new Promise((resolve) => { setTimeout(resolve, ms) })

async function dbQuery() {
  const start = Date.now();
  await sleep(1000);
  const end = Date.now();
  console.log(end - start);
}

async function main() {
  const list = [1, 2, 3];
  const promises = list.map(m => dbQuery(m));
  await Promise.all(promises);
}

main();

Output:

node-space node is-parallel.js
1003
1009
1009

I want to dbQuery function to be executed at same time when invoke all 3 promises. Now i’m invoking them and pushing into the array and awaiting them, I believe it is not truly parallel, it like calling each function and pushing it to array in serial fashion.

sleep function i have added is just so simulate something async.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Async code in Javascript allows interleaving of code execution, but not parallel execution.

Parallelism can be achieved in Node using the worker threads built-in module. If you want a web standard solution, you could also user Web Workers.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading