0

Situation

I want to apply multi-threading in Node but it does not work. I already searched the web but I have not found tutorials on what I want which is multi-threading using "Promises".

Minimal reproducible example

let promises = [];

for(let j = 1; j <= Os.cpus().length; ++j)
{
    promises.push(new Promise((resolve, reject) =>
    {
        try
        {
            //Some synchronous code.
            //...
            resolve(val);
        }
        catch(e)
        {
            reject(e);
        }
    }));
}

//Evaluate the result.
const results = await Promise.all(promises);

Problem

I keep track of the execution of each promise by printing to the console and I see that the promises are executed in chronological order. One promises execution only starts if the promise before that finished execution. From my understanding this is the behaviour if I put an "await" before every "Promise" construction but I did not!

What I need

I come from C++ where this approach would work. I just want to assign a thread to each CPU core and then wait for every thread to finish execution (see the last line). The threads shall be executed simultaneously.

Spixmaster
  • 123
  • 1
  • 2
  • 13
  • 2
    NodeJS programs are signle thread. You cannot spawn thread from NodeJS program. You need to spawn worker process (using `child_process` module) to run multiple process. – Niyoko Jul 05 '20 at 10:30
  • 2
    Promises are **not** threads. – Quentin Jul 05 '20 at 10:30

0 Answers0