Is this correct code in Node.js? (variable scoping)
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:
var uuu = req.params.userid;
You are capturing the current value of req.params.userid
in the local variable uuu
and then uuu
is captured by the callback closure. However, if you accidentally did this:
uuu = req.params.userid;
Then you'd be capturing the req.params.userid
value in the global uuu
and each of your callbacks would share the same uuu
and you'd have the usual closure problem. Each of your
function(user_object) { ... }
anonymous functions are separate and distinct entities with their own separate and distinct uuu
variables (given that you say var uuu
rather than uuu
of 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, uuu
won't matter at all.
精彩评论