4

I need to run two tasks in parallel in Node.js like how we spawn two threads in Java. I looked though all of the documentation related to promises and async/await.

I went through the following threads:

  1. Parallel function calls in Node.js
  2. Parallel operations with Promise.all?

Even if I use Promise.all, the code is getting executed sequentially.

I couldn't find a way to do so. I see that HTTP.get executes in the background, and once the results are available, it returns the response in callback. Until that happens, my program can perform other tasks. Can I do something like this to accomplish parallelism in my own code?

I have the following code. I want to make sure that func1 and func2 run in parallel.

I am expecting an output in the following order:

calling func1
calling func2
called all functions
promise 1 done!
promise 2 done!

This is my code

function func1() {

  let promise = new Promise((resolve, reject) => {
    try {
    for(var q=0;q<10000;q++) {
        console.log(q);
    }
    resolve("promise 1 done!")
    } catch(e) {
    reject(e);
    }
  });
  return promise;
}

function func2() {

  let promise = new Promise((resolve, reject) => {
    try {
    for(var r=0;r<10000;r++) {
        console.log(r);
    }
    resolve("promise 2 done!")
    } catch(e) {
    reject(e);
    }
  });
  return promise;
}


function func() {
    console.log("calling func1");
    var promise1 = func1();

    console.log("calling func2");
    var promise2 = func2();

    console.log("called all functions");
    //do some other task

    promise1
.then(result => { console.log("Promise 1 : "+result); })
.catch(error => { console.log("Promise 1 err : "+error ); });

    promise2
.then(result => { console.log("Promise 2 : "+result); })
.catch(error => { console.log("Promise 2 err : "+error ); });
}

func();
                                                                                                                                                                                                    

In short, how can I make the two for loops execute in parallel? Is it possible in Node JS or am I missing something?

Adil Hussain
  • 30,049
  • 21
  • 112
  • 147
Albie Morken
  • 215
  • 1
  • 4
  • 14
  • Possible duplicate of [Parallel function calls in Node.js](https://stackoverflow.com/questions/14035015/parallel-function-calls-in-node-js) – Mr X Jun 06 '18 at 08:30
  • 1
    I went through that thread. I even went through https://stackoverflow.com/questions/42772401/parallel-operations-with-promise-all. But it doesn't answer my question. How do I create a non-blocking promise. Even though I have a for loop there, which is blocking, how can I create two such for loops running in parallel ? I cannot use setTimeOut. – Albie Morken Jun 06 '18 at 09:01
  • 1
    Asynchronous code using Promises or async/await is different than parallel code. Asynchronous code is still running on the same thread, just in a non blocking way. To run something in parallel you could use `child_process` or `cluster` modules, which will `spawn` or `fork` new nodejs processes that will run on new cpu cores. – BradStell Jan 27 '20 at 21:42

3 Answers3

3

You can use Promise.all. Example:

var promise1 = func1();
var promise2 = func2();

Promise.all([promise1, promise2])
  .then(results => console.log(results)); // [promise1Result, promise2Result]

If you want promises to resolve one after the other you can do:

func1().then(result1 => {
  // do something with the result
  return func2();
})
.then(result2 => {
  // do something with the result
})
.catch(err => console.log(err));
Omar
  • 343
  • 1
  • 11
  • 12
    I tried Promose.all, but still the func1 and func2 is getting executed sequentially. They are not running in parallel. – Albie Morken Jun 06 '18 at 08:52
  • 1
    This is not running in parallel, but rather asynchronous. Nodejs is single threaded. asynchronous code still runs on the same cpu core/thread. True parallel execution could be accomplished using `child_process` or `cluster` modules, which launch new nodejs processes. – BradStell Jan 27 '20 at 21:41
1

I know this a old question but no one pointed out an mistake in the original question's code.

function func() {
    console.log("calling func1");
    var promise1 = func1();      

    console.log("calling func2");
    var promise1 = func2();    // <- Mistake: should be assigned to promise2 not promise1

    console.log("called all functions");
    //do some other task

    promise1
.then(result => { console.log("Promise 1 : "+result); })
.catch(error => { console.log("Promise 1 err : "+error ); });

    promise2
.then(result => { console.log("Promise 2 : "+result); })
.catch(error => { console.log("Promise 2 err : "+error ); });
}
KingAndrew
  • 1,164
  • 4
  • 21
  • 41
1

async function smsNotify(mobileNumber, msg){
    // send sms
}

async function emailNotify(emailId, msg){
    // send email
}

async function pushNotify(fcmId, msg){
    // push notifications
}



/**
* Notify User by sms , email , push notification
*/

async function notify(userDetails){
    const { mobileNumber, emailId, fcmId, msg } =  userDetails

    // prepare async calls
    const asyncCalls = [];

    asyncCalls.push(smsNotify(mobileNumber, msg));
    asyncCalls.push(emailNotify(emailId, msg));
    asyncCalls.push(pushNotify(fcmId, msg));

    try{
        const result = await Promise.all(asyncCalls);
    }catch(err){
        console.error("Error Occur: ", err.message);
    }
}
Jhamman Sharma
  • 147
  • 1
  • 2