My goal is demonstrate the power of a non blocking code with node.js, so I try simulate a I/O event with a sleep statement, but my effort keep failing:
我的目标是使用node.js演示非阻塞代码的强大功能,因此我尝试使用sleep语句模拟I / O事件,但我的努力仍然失败:
var http = require('http');
var url = require('url');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
if( url.parse(request.url).pathname == '/wait' ){
var startTime = new Date().getTime();
while (new Date().getTime() < startTime + 15000);
response.write('Thanks for waiting!');
}
else{
response.write('Hello!');
}
response.end();
}).listen(8080);
console.log('Server started');
When I access http://localhost:8080/wait after http://localhost:8080, both are waiting for the loop.
当我在http:// localhost:8080之后访问http:// localhost:8080 / wait时,两者都在等待循环。
Any tips?
1 个解决方案
#1
2
setTimeout is your friend, so are braces.
setTimeout是你的朋友,大括号也是。
app.use(function(request, response, next) {
var doIt, startTime;
if (request.path === '/wait') {
startTime = new Date().getTime();
doIt = function() {
if (new Date().getTime() < startTime + 15000) {
response.write('Thanks for waiting!');
return setTimeout(doIt, 1000);
} else {
return response.end();
}
};
return doIt();
} else {
response.write('Hello!');
return response.end();
}
});
#1
2
setTimeout is your friend, so are braces.
setTimeout是你的朋友,大括号也是。
app.use(function(request, response, next) {
var doIt, startTime;
if (request.path === '/wait') {
startTime = new Date().getTime();
doIt = function() {
if (new Date().getTime() < startTime + 15000) {
response.write('Thanks for waiting!');
return setTimeout(doIt, 1000);
} else {
return response.end();
}
};
return doIt();
} else {
response.write('Hello!');
return response.end();
}
});