在 Javascript 中通过变量作用域维护变量
我在处理我正在制作的 Node.js 应用程序中的变量作用域时遇到了麻烦,通常我了解变量作用域如何在函数内部/周围工作(在本例中为匿名回调函数)。
我正在努力解决的是通过匿名回调链/漏洞维护变量的最佳方式是什么。通常我可以将变量传递给函数,但是因为我使用的是 mongoose (mongodb ORM),所以我无法传递我自己的变量。因此必须在每一步深入到函数中一遍又一遍地定义变量。打回来。
这样做的最佳方法是什么?
下面是我的代码,当我想使用它们来发推文时,我最终得到了未定义的变量:
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);
}
});
}
});
}
});
当然有更好的方法来处理这个问题...... 非常感谢任何帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用闭包作用域(
tag.user
可通过闭包获得)或使用.bind
将变量绑定到函数。例如,我们通过执行以下操作将
userAName
变量柯里化到匿名函数中: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