简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM