+ 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
4 ответов
+ 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 !
+ 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.
+ 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
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