How to run a large loop of 20 secs without blocking the main thread in nodejs ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to run a large loop of 20 secs without blocking the main thread in nodejs ?

If I run a loop that executes in 20 secs, it causes my express js server to not able to respond any request for 20secs. Is there are any way to run a large loop in parallel without blocking the main thread in node js

22nd Mar 2022, 5:19 PM
Abhay
Abhay - avatar
4 Answers
+ 2
Mustafa A bro, async function will also blocks the main thread in this case... Because it put this loop in a event loop queue and then when the main thread got free, it shift the loop to the main thread, and then the main thread get blocked and if any request came to server at that time it had to wait for 20secs for the loop to finish first.... Actually i already founded the solution for this problem, which is worker threads ( Parallel Processing / multi threading in NodeJS ). Using worker thread, we can run loop in parallel without blocking the main thread !
25th Mar 2022, 6:27 PM
Abhay
Abhay - avatar
+ 1
Look up async functions. Basically, NodeJS isn't multithreaded, in the sense that you can create and run new threads. But, it has an asynchronous execution stack. Async function calls are added there. Async functions won't block the main thread.
23rd Mar 2022, 12:04 AM
Mustafa A
Mustafa A - avatar
+ 1
Mustafa A Bro could u tell me those async functions, in which, I can execute a loop which completes in 20secs and does not blocks the main thread .... Bro plzzz
24th Mar 2022, 1:25 AM
Abhay
Abhay - avatar
0
Abhay It's just a function, but the execution is asynchronous. You don't get an result after calling the function. You will instead get a promise that there will be a result in the future. You can the continue in the main thread. You can use the "then" method of the promise object to hook it up with a callback function to handle the result when you finally get it. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
24th Mar 2022, 6:16 AM
Mustafa A
Mustafa A - avatar