[英]Global variable inside function scope not working - async.series
I'm trying to set a global variable for the function in order to use it in all functions inside a scope. 我试图为该函数设置一个全局变量,以便在范围内的所有函数中使用它。 Functions are called one after another using async.series
: 使用async.series
调用函数:
exports.update = function(req, res, next){
var result = {}; // setting global var for the scope
var function1 = function(callback) {
MyModel.findOne(conditions)
.lean()
.exec(function(err, docs) {
if (err) {
return callback(err, null);
}
result.docs = docs; // assigning function result to global var
return callback(null, 'done');
});
};
var function2 = function(callback) {
var fieldsToSet = {
// ...
somefield: result.docs.someproperty // error here result.docs = null
};
Mymodel.create(fieldsToSet, function(err, record) {
// ...
});
};
};
require('async').series([function1, function2]);
};
Returns error: 返回错误:
TypeError: Cannot read property 'someproperty' of null
How in this case I get the property? 在这种情况下,我如何获得财产? Thank you. 谢谢。
Old answer 旧答案
Declare result
outside of exports.update
. 在exports.update
之外声明result
。 Must work in this case. 在这种情况下必须工作。
EDIT : Probably make result
equal to an empty object inside the function as well, if that's what you want. 编辑:可能使result
等于函数内部的空对象,如果那是您想要的。
New answer as of December 17th 截至12月17日的新答案
@ASem : if you're still up for it, maybe define result.docs = {};
@ASem:如果您仍然努力,可以定义result.docs = {};
right under result
? result
正确吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.