Javascript Node.js中的Functionscope和回调
因此,我必须在循环中计算一些Javascript Node.js中的Functionscope和回调,javascript,node.js,Javascript,Node.js,因此,我必须在循环中计算一些共享。在该循环的每次迭代中,我都必须从数组中获取一个名为rent的变量。因此,我将calculate函数从数据库中分离出来 var calculate = function() { while(count < 100) { var share = 50; var shareArray = []; for(var i = 0; i < 100; i++) { var pens
共享。在该循环的每次迭代中,我都必须从数组中获取一个名为rent
的变量。因此,我将calculate
函数从数据库中分离出来
var calculate = function() {
while(count < 100) {
var share = 50;
var shareArray = [];
for(var i = 0; i < 100; i++) {
var pension = share*2; // mathematical stuff
// Gets a rent from a database and returns it in a callback
getRent(modules, share, function(rent) {
share = rent*foo; // some fancy mathematical stuff going on here
// I need to get the share variable above out of its function scope
});
// I need the share variable right here
shareArray.push(share); // the value of share will be for i = 0: 50, i= 1: 50 ...
// This is not what i want, i need the share value from getRent()
}
count++;
}
}
所以问题是:我如何“返回”共享
:
getRent(modules, share, function(rent) {
share = rent*foo; // some fancy mathematical stuff going on here
// I need to get the share variable above out of its function scope
});
以任何方式?您希望使用库的方法(npm install async
)来简化此过程:
var count = 0;
var shareArray = [];
async.whilst(
function () {
return count < 100;
},
function (next) {
count++;
getRent(function(rent) {
// What does modules do anyway??
// Dont know where foo comes from...
shareArray.push(rent*foo); // some fancy mathematical stuff going on here
next();
});
},
function (err) {
console.log(shareArray);
// Do sth. with shareArray
}
);
var计数=0;
var shareArray=[];
异步的(
函数(){
返回计数<100;
},
功能(下一个){
计数++;
获取租金(功能(租金){
//模块到底做什么??
//不知道福从哪里来。。。
sharearay.push(rent*foo);//这里有一些奇特的数学知识
next();
});
},
功能(err){
log(shareArray);
//用数组做某事
}
);
如果可以并行请求所有100个调用,也可以使用该函数。如果getRent
是异步的,则无法同步获得结果。基本上,您不知道getRent
最终将为其回调提供的值,直到它最终返回它。所以这不是功能范围的问题,而是时间的问题。您只需等待getRent
完成它的工作,然后才能获得rent
的值。您需要重构代码,以便calculate
也是异步的
比如:
// Refactor calculate to be async:
function calculate(cb) {
var data = [];
for ( var i=0; i<100; i++ ) {
getRent(function (rent) {
data.push(rent);
if ( data.length === 100 ) cb(data);
});
}
}
// And then use it async:
calculate(function (data) {
// data array arrives here with 100 elements
});
//将计算重构为异步:
函数计算(cb){
var数据=[];
对于(var i=0;i何谓“getFromDB()”看起来像?我不明白这是怎么回事,因为从数据库中获取数据几乎肯定也会涉及到一个异步步骤。而且,从性能角度来看,如果您可以执行一个查询来获取所需的所有值,而不是对每个值执行单独的查询,那么您的境况肯定会好得多。一次执行一个查询会慢得多一次也没有。对不起。这只是一个构造的示例。真正的代码很难解释这一点。只要假设这是可行的。Mhh maybee我会编辑它。基本问题是,对于异步系统,你必须将逻辑从内到外转换。不,我在发布了下意识的wtf后得到了这个。对不起
// Refactor calculate to be async:
function calculate(cb) {
var data = [];
for ( var i=0; i<100; i++ ) {
getRent(function (rent) {
data.push(rent);
if ( data.length === 100 ) cb(data);
});
}
}
// And then use it async:
calculate(function (data) {
// data array arrives here with 100 elements
});