[英]asynchronous JavaScript static function variable
I have a problem with a "static" function in javascrip (nodejs server). 我在javascrip(nodejs服务器)中的“静态”功能有问题。
User.create = function(data, _callback){
var node = db.createNode(data);
var _user = new User(node);
_user.save(function(err){
if(err) return callback(err, null);
_user.index(function(err){
if(err) return callback(err, null);
callback(null, _user);
})
})
};
If I call this function twice the _user variable in the internal callback function takes the new value, it seems it overrides the function var instead of allocate a new one. 如果我两次调用此函数,则内部回调函数中的_user变量将使用新值,似乎它会覆盖函数var而不是分配新值。
I need calling this function to allocate a new variable, so it waits save and index functions to complete without changing _user variable. 我需要调用此函数来分配新变量,因此它在不更改_user变量的情况下等待保存和索引函数完成。
JavaScript variables are indeed function scoped, so there wouldn't be any explanation for var _user
not defining a new variable on subsequent runs. JavaScript变量的确是函数作用域的,因此不会对
var _user
在后续运行中未定义新变量的任何解释。
Looking at the code, I would be more suspicious of what's happening in your User constructor - perhaps it contains some scoping or other logical issues resulting in identical users being created on subsequent calls. 查看代码,我会更怀疑您的User构造函数中发生的事情-也许它包含某些范围界定或其他逻辑问题,导致在后续调用中创建相同的用户。 Similar "suspects" would be the
data
parameter getting passed in, as well as db.createNode()
. 类似的“怀疑”将是传入的
data
参数,以及db.createNode()
。 Only suggesting these areas, because it's more likely that there's a programmatic issue at play, rather than JavaScript not following the rules :) 仅建议这些方面,因为更有可能出现程序问题,而不是JavaScript不遵守规则:)
Also, I noticed that your User.create
function accepts a parameter called _callback
, but later on is invoking callback
. 另外,我注意到您的
User.create
函数接受一个名为_callback
的参数,但稍后将调用callback
。 I don't know if that's a typo in your example, or if you're accidentally invoking a callback from a higher scope not shown in the example, but that could produce weird behavior. 我不知道这是您的示例中的错字,还是不小心从示例中未显示的更高范围调用回调,但这可能会产生奇怪的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.