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?