I'm new to node.js, I tried to use setTimeout to simulate long connections and hope it act asynchronously.
var http = require('http');
http.createServer(function (request, response) {
console.log('New request @ ' + request.url);
(function (response) {
setTimeout(function () {
console.log('Time is up');
response.writeHead(200, {"Content-Type": "text/plain"});
response.end('Hello World\n');
}, 3000);
})(response);
}).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');
But, the code above perform like a synchronous single thread app, which can only handle one request per 3 seconds.
I thought everything in node.js should act asynchronously. So, what's the problem here?
setTimeout() is an asynchronous function, meaning that the timer function will not pause execution of other functions in the functions stack.
setTimeout — new way: js development team, we are now able to use async/await syntax while dealing with setTimeout() functions. This feature was initially implemented in Node v.
setTimeout() can be used to schedule code execution after a designated amount of milliseconds. This function is similar to window. setTimeout() from the browser JavaScript API, however a string of code cannot be passed to be executed.
This can be solved with an async function: const delay = (duration) => new Promise(resolve => setTimeout(resolve, duration)); const asyncFunc = async (... args) => { await delay(1000); return computeResult(... args); };
The SetTimeout
is async, you don't need that anonym function in the middle, just write this.
var http = require('http');
http.createServer(function (request, response) {
console.log('New request @ ' + request.url);
setTimeout(function () {
console.log('Time is up');
response.writeHead(200, {"Content-Type": "text/plain"});
response.end('Hello World\n');
}, 3000);
}).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');
If you produce 10 concurent request the total comp time will be around 3sec, which means it is async. You can use the ab tool to check, or if you program node, maybe easier to install http-perf. and run nperf -c 10 -n 10 http://127.0.0.1:8124
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With