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?
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With