如果我太粗鲁了,我很抱歉。我已经尝试过搜索功能,但作为一个相对较新的人,我正在努力寻找解决方案。我想我可能没有搜索到正确的关键字。
我的Node.js应用程序中有一个路由,其中有两个forEach循环。我希望forEach循环1结束,然后启动forEach循环2。当这一切完成后,我想调用我的res.redirect。目前,该路由直接到达res.redirect,并且似乎没有完成forEach循环。
代码:
// Auto-populate entries
router.post("/populate", middlewareObj.isLoggedIn, function(req, res) {
var baseData = []
//lookup Plan using ID
Plan.findById(req.params.id, function(err, foundPlan) {
if (err) {
console.log(err);
res.redirect("/plans");
} else {
BaseData.find({
"contributingRegion": foundPlan.contributingRegion
}, function(err, foundRecords) {
foundRecords.forEach(function(record) {
baseData.push(record)
baseData.save
});
//Create entries & push into plan
baseData.forEach(function(data) {
if (includes(req.body.orgs, data.org)) {
Entry.create(data, function(err, entry) {
if (err) {
console.log(err);
} else {
entry.author.id = req.user._id;
entry.author.username = req.user.username;
entry.save();
foundPlan.planEntries.push(entry);
foundPlan.save();
}
})
}
})
res.redirect('/plans/' + foundPlan._id);
});
}
});
});发布于 2018-01-26 23:53:52
有很多方法可以实现这一点,例如,你可以使用promises或async module,你也可以使用recurrent functions,我将提供一个带有异步模块的解决方案,因为它让你了解异步函数是如何工作的,以及如何控制它们:
async.each( baseData, function (data, next) {
if (includes(req.body.orgs, data.org)) {
Entry.create(data, function(err, entry) {
if (err) {
// stop iterating and pass error to the last callback
next(err);
} else {
entry.author.id = req.user._id;
entry.author.username = req.user.username;
entry.save();
foundPlan.planEntries.push(entry);
foundPlan.save();
// next iteration
next();
}
});
} else {
// next iteration
next();
}
}, function (err) {
// This function runs when all iterations are done
if (err) throw err;
res.redirect('/plans/' + foundPlan._id);
} );https://stackoverflow.com/questions/48464355
复制相似问题