Simulating Asyncronicity
Video Course on Real-Time HTML5 with Node.jschallenge: create a setTimeout that will generate a random number, then another timeout to send back the response
my solution (lines #5-24):
function handleHTTP(req,res) {
if (req.method === "GET") {
if (req.url === "/") {
function createTest(cb) {
var newtext = "Hello World" + Math.random();
setTimeout(function (){
cb(newtext);
},500);
}
function sendresponse(contents, cb){
res.writeHead(200,{
"Content-type": "text/html"
});
res.end(contents);
if (cb){
cb();
}
}
setTimeout(function (){
createTest(sendresponse);
}, 1000);
}
else {
res.writeHead(404);
res.end("Couldn't find it!");
}
}
else {
res.writeHead(403);
res.end("No, no, don't do that!");
}
}
var http = require("http");
var httpserv = http.createServer(handleHTTP);
httpserv.listen(8006,"localhost");
his solution is with anonymous functions:
setTimeout(function(){
var num = Math.random();
setTimeout(function(){
res.end("Hello World:" + num);
}, 1000);
}, 1000);