'Node.js running two functions in parallel
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:
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?
Solution 1:[1]
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));
Solution 2:[2]
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 ); });
}
Solution 3:[3]
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);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Omar |
| Solution 2 | KingAndrew |
| Solution 3 | Jhamman Sharma |
