As per Understanding the node.js event loop, node.js supports a single thread model. That means if I make multiple requests to a node.js server, it won't spawn a new thread for each request but will execute each request one by one. It means if I do the following for the first request in my node.js code, and meanwhile a new request comes in on node, the second request has to wait until the first request completes, including 5 second sleep 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 first request to complete, or can I call sleep on specific thread only?
Please consider the deasync module, personally I don't like the Promise way to make all functions async, and keyword async/await anythere. And I think the official node.js should consider to expose the event loop API, this will solve the callback hell simply. Node.js is a framework not a language.
If you are referring to the npm module sleep, it notes in the readme that
sleep
will block execution. So you are right - it isn't what you want. Instead you want to use setTimeout which is non-blocking. Here is an example:For anyone looking to do this using es7 async/await, this example should help:
In case you have a loop with an async request in each one and you want a certain time between each request you can use this code:
This examples waits 1 second after each request before sending the next one.