开发者

Maintaining variables through variable scope in Javascript

开发者 https://www.devze.com 2023-04-01 03:36 出处:网络
I\'m having trouble grappling with variable scope withing a Node.js application I\'m making, generally I understand how variable scope works in/around a function (in this instance, anonymous callback

I'm having trouble grappling with variable scope withing a Node.js application I'm making, generally I understand how variable scope works in/around a function (in this instance, anonymous callback functions).

What I'm battling with is what is the best way of maintaining vairables through a chain/hole of anonymous callbacks. Where as normally I could pass the variables to the functions, but because I'm using mongoose (mongodb ORM) I cant pass my own variables in. and so have to either resort to defining the variables over and over at each step deeper into the callback.

What is the best way of doing this?

Below is my code where I end up getting variables undefined by the time I want to use them for tweeting:

var userBid = tag.user;

User.find({id: userAid}, function(err, userA){

  if (err) {console.log("Error getting user A for tweeting ", err)}
  else {
    var userAName = userA.twitter.screenName;
    var userBid2 = userBid;
    User.find({id: userBid2}, function(err, userB){

      if (err) {console.log("Error getting user B for tweeting ", err)}
    开发者_如何学运维  else {

        var action = "@"+ userAName + " just claimed some of @" + userB.twitter.screenName + " 's turf as their own.";

        twitterClient.updateStatus(action, function(err, resp){
          if (!err) {
            console.log("Tweeted: ", action );
          } else {
            console.log("TwitBot error:", err);
          }
        });
      }
    });
  }
 });

Surely there is a better way of handling this... ANy help is much appreciated.


User.find({
    id: userAid
}, function(err, userA) {
    if (err) throw err;
    else {
        User.find({
            id: tag.user
        }, (function(userAName, err, userB) {
            if (err) throw err;
            else {
                var action = "@" + userAName + " just claimed some of @" + userB.twitter.screenName + " 's turf as their own.";
                twitterClient.updateStatus(action, function(err, resp) {
                    if (!err) {
                        console.log("Tweeted: ", action);
                    } else {
                        console.log("TwitBot error:", err);
                    }
                });
            }
        }).bind(null, userA.twitter.screenName));
    }
});

Either use closure scope (tag.user is available through closures) or use .bind to bind variables to a function.

For example we've curried the userAName variable into the anonymous function by doing

(function(userAName, normal, arguments, here) {

}).bind(null, userAName));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号