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.
>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.