function user(req,res){
var uuu = req.params.userid;
processUserObject(uuu, function(user_object){ //This could take a long time...
console.log(uuu);
res.send(JSON.stringify(user_object));
});
};
app.get('/:userid',function(req,res){
user(req,res);
});
First, assume that the site gets lots of hits. (thousands per second!)
When a user hits the page with his ID, will console.log(uuu) output the correct ID? What I’m worried (in regards to variable scoping) is that when person A hits the page and goes through processUserObject, it could take a long time, during which person B hits the page and changes uuu…resulting in console.log to output person B’s ID instead of person A’s ID.
Side note: I have this worry because when I was new to Node.js, I forgot to initialize some variables with var. When my site got lots of hits, my users noticed that they were getting info from other user’s hits…ouch.
Yes,
console.log(uuu)will log the right value. When you say this:You are capturing the current value of
req.params.useridin the local variableuuuand thenuuuis captured by the callback closure. However, if you accidentally did this:Then you’d be capturing the
req.params.useridvalue in the globaluuuand each of your callbacks would share the sameuuuand you’d have the usual closure problem. Each of youranonymous functions are separate and distinct entities with their own separate and distinct
uuuvariables (given that you sayvar uuurather thanuuuof course).BTW, if you do end up with a billion requests per second the heat from your overworked CPUs will melt the walls between this world and the next thus releasing the elder gods from R’lyeh. And if that happens,
uuuwon’t matter at all.