How to hide a thread in node.js without affecting other threads?

By Understanding the node.js event loop , node.js supports a single-thread model. This means that if I make several requests to the node.js server, it will not generate a new thread for each request, but will execute each request one by one. This means that if for the first request in my node.js code I do the following: the first request comes to node, the second request should wait for the first request to complete, including a 5 second wait time. Right?

var sleep = require('sleep'); sleep.sleep(5)//sleep for 5 seconds 

Is there a way that node.js can spawn a new thread for each request so that the second request does not have to wait for the completion of the first request, or can I only call a specific thread?

+49
multithreading asynchronous
Nov 19 '12 at 5:50
source share
2 answers

If you reference the npm sleep module, readme indicates that sleep block execution. So you are right - this is not what you want. Instead, you want to use setTimeout , which does not block. Here is an example:

 setTimeout(function() { console.log('hello world!'); }, 5000); 



For those who want to do this using es7 async / await, this example should help:

 const snooze = ms => new Promise(resolve => setTimeout(resolve, ms)); const example = async () => { console.log('About to snooze without halting the event loop...'); await snooze(1000); console.log('done!'); }; example(); 
+84
Nov 19 '12 at 6:01
source share

If you have a loop with an asynchronous request in each of them, and you want a certain time between each request, you can use this code:

  var startTimeout = function(timeout, i){ setTimeout(function() { myAsyncFunc(i).then(function(data){ console.log(data); }) }, timeout); } var myFunc = function(){ timeout = 0; i = 0; while(i < 10){ // By calling a function, the i-value is going to be 1.. 10 and not always 10 startTimeout(timeout, i); // Increase timeout by 1 sec after each call timeout += 1000; i++; } } 

These examples wait 1 second after each request before sending the next one.

0
Apr 28 '17 at 15:45
source share



All Articles