0

As far as I know, NodeJS doesn't run promises in parallel, it runs them concurrently as it is a single threaded event loop architecture. Ability to run things in parallel by creating a new child process to take advantage of multi-core CPUs. but when i run this test it shows the result of running in parallel. please help me explain

const a = new Promise(resolve => setTimeout(() => resolve("a"), 2000))
const b = new Promise(resolve => setTimeout(() => resolve("b"), 2000))
const c = new Promise(resolve => setTimeout(() => resolve("c"), 2000))
const begin = Date.now();
async function test() {

  const promises = [a, b, c];
  const [output1, output2, output3] = await Promise.all(promises);
  return `parallel is done: ${output1} ${output2} ${output3}`;

}
test().then((arr)=>{
    console.log(arr);
    console.log( "time :", Date.now()- begin);
})
// parallel is done: a b c
//time : 2010
Snirka
  • 602
  • 1
  • 5
  • 19
shady
  • 11
  • 1
    Does this answer your question? [Is Node.js native Promise.all processing in parallel or sequentially?](https://stackoverflow.com/questions/30823653/is-node-js-native-promise-all-processing-in-parallel-or-sequentially) – Xth Jun 27 '21 at 22:59
  • 2
    "*when i run this test it shows the result of running in parallel.*" - I don't see how your test would distinguish between concurrent and parallel timeouts? – Bergi Jun 27 '21 at 23:06
  • i think if it runs concurrently it will be 6s – shady Jun 27 '21 at 23:24
  • 1
    No, that's sequential. "concurrent" literally means they happen "at the same time". – Bergi Jun 28 '21 at 03:33
  • `Promise.all` doesn't "run" promises at all. It just monitors a collection of promises for their completion. And yes, promises can run in parallel. That's pretty much the whole point of asynchrony. – JLRishe Jun 28 '21 at 04:23

2 Answers2

-1

It doesn't run in parallel, but I believe your question is exactly the point of this video: https://www.youtube.com/watch?v=mvWSD-5G4Yw

Dharman
  • 30,962
  • 25
  • 85
  • 135
-1

just because its single thread it doesnt means it can do only one thing.

yes, you can spawn, but most things are done like:

"hey, ur done?"
"nope"
goes ask whatever needs to be done next while waiting

its basically a big while true that goes around checking stuff until things are done.

Noriller
  • 342
  • 1
  • 4
  • 12