【发布时间】:2015-07-02 17:24:23
【问题描述】:
在POST 类型的Form Action 上,我们获取Node.JS/Express 中的所有值并尝试将其保存到MongoDB。
隐藏字段从前端 javascript 确定属性的长度,并且它的值被更新为隐藏字段的值。
这个长度在后端(节点)中用于迭代项目列表。
我有一个async.waterfall 函数和一个for loop 在里面运行,就像这样。
async.waterfall([
function(callback){
var itemLength = req.body.itemLength;
var itemProp,itemComponent;
var destination;
var destinationsArray =[];
for(var k=1; k<=itemLength; k++){
destination = new Destination({
name: req.body['destinationName'+k],
});
itemComponent = {
"itemCompProp" : req.body['itemCompProp'+k]
};
itemProp = new ItemProp({
itemComponent: itemComponent
});
itemProp.save(function(err,itemPropSaved){
destination.newProperty = itemPropSaved._id
destination.save(function(err,destinationSaved){
if(err){
console.log("Error== " + err);
}
else{
destinationsArray.push(destinationSaved._id);
}
});
});
}// End of For
callback(null,destinationsArray);
},
function(destinationsArray,callback){
var brand = new Brand({
name : req.body.brandName,
});
brand.save(function(err,brandSaved){
if(err){
console.log("Error== " + err);
}else{
console.log('Brand Saved');
}
});
callback(null);
}
], function (err, status) {
if(err){
req.flash('error', {
msg: 'Error Saving Brands'
});
console.log("Error : " + err);
}
else{
console.log("Brand Saved.");
req.flash('success', {
msg: 'Brand Successfully Added!'
});
}
});
res.redirect('/redirectSomewhere');
当我们运行此程序时,destinationsArray 首先作为null 返回,而不是通过for loop 然后在一定长度(itemLength) 的目的地上返回正确的destinationsArray 值。
我们希望这个过程是同步的。我们还尝试使用包装for Loop 的闭包,但无济于事。
我们不能使用async.eachSeries 代替for Loop,因为我只是在迭代一个数字属性并且我们没有任何documents to iterate over
在async.waterfall 内运行for Loop 的任何可行解决方案?
提前干杯和感谢。
【问题讨论】:
标签: javascript node.js mongodb asynchronous mongoose