我从视图向控制器发送了许多值数组。例如:
year: ['2015','2016','2017']
cash: ['...','...','...']
.
.
.
这些数组中每个数组的第0个索引在cashflow数据库表中形成一条记录。第一个记录另一个,依此类推......现金流是一个集合内部"属性"模型。我需要创建这些'现金流'每当一个“财产”的记录时,就会反复进行。已创建。
我正在使用sails框架。我无法迭代地创建这些记录并立即渲染它们。我不确定是否需要使用异步任务来完成。
Property.create(reqParams).exec(function(err, property) {
if (err) {
...
} else {
var index = 0;
var asyncTasks = [];
for (index = 0; index < reqParams.year.length; index++) {
asyncTasks.push(function(callback) {
CashFlowProjections.create({
year: reqParams.year[index],
belongsTo: property.id,
cash: reqParams.cash[index],
...)
.exec(function(err, cashflows) {
callback(err, cashflows);
});
});
}
async.parallel(asyncTasks, function(err, results) {
if (err) {
res.handleError(0, err);
} else {
res.view('property/preview', {
cashflows: results[0],
...
});
}
});
}
}
});
但是上面的代码是错误的,因为&#39;索引&#39;最终成为所有记录的相同值,并且记录创建失败。
我也尝试过没有异步任务,但我遇到了一个&#34; res.view&#34;在创建现金流记录之前执行。有人能引导我吗?
答案 0 :(得分:3)
The problem is with the scope of the variable index
. index
is scoped to the function that begins on line 1. asyncTasks
becomes an array of functions which are closures - they share the variable with their enclosing scope. Since these functions are called asynchronously, after the for
loop has finished, index
has a value of reqParams.year.length
by the time they are called.
To get round this, you could create a separate scope for each function, and in these scopes make a copy of index
, which will not be affected by the index++
of the original index
. Like this:
for (index = 0; index < reqParams.year.length; index++) {
(function(index) {
asyncTasks.push(function(callback) {
CashFlowProjections.create({
year: reqParams.year[index],
belongsTo: property.id,
cash: reqParams.cash[index],
...})
.exec(function(err, cashflows) {
callback(err, cashflows);
});
});
})(index);
}
If you do this, there are really two separate variables called index
:
for
line and also in })(index);
. Its value starts as 0 and is incremented each time it goes through the loop.function(index)
. This overrides the original one, but only inside the function definition. In fact this is really several separate scopes: every time it goes through the loop, it creates a new (anonymous) function and calls it, and calling the function creates the scope. Its value is set to whatever the outer index
was at the time the loop was run, is never changed after that, and is used when async.parallel
runs the task.So if you prefer you can rename one of the two variables to avoid confusion.