我很新的nodejs的async.forEach和我有困难的聚合嵌套的forEach循环的结果。nodejs嵌套forEach,汇总结果
我有一个动态范围的日期和一些屏幕,我想循环,并创建一个时间表或更新现有的。该部分按设计工作。但是,我无法构建一个已创建并已更新的所有时间表的数组。我似乎只得到第一个,但没有休息。
我已经尝试了很多不同的方式调用回调,但是我得到的最多的只是我的输出数组中的一个项目。
我试着从本网站不同的方法,但我还没有得到运气: http://www.sebastianseilund.com/nodejs-async-in-practice
什么是处理这种情况的最好方法是什么?
下面是我的下调回环remoteMethod:
===========================
Schedule.Reservation = function(PostData, cb) {
var output = []; // <-- I would like to return this array ... which is report of all created and updated schedules
try {
// create all models
async.series([
function validateData(callback) {
callback();
},
function processReservation(callback) {
var screens = PostData.Screens;
var dates = getDateRangeArray(PostData);
async.forEach(dates, function(liveDate, callbackDate)
//for (var d = new Date(PostData.StartDate); d <= end; d.setDate(d.getDate() + 1))
{
async.forEach(screens, function(screen, callbackScreen)
//for (var s=0;s<screens.length;s++)
{
if (screen.details)
async.forEach(screen.details.BookingInformation, function(frame, callbackFrame) {
if ((frame.BlockedDays == 0) || (!isBlocked)) {
Schedule.findOne({
where: {
LiveDate: liveDate,
ScreenID: screen.id,
FrameID: frame.FrameID,
Remaining: {
gte: PostData.RequiredSlots
}
}
}, function(errSchedule, schedule) {
var scheduleLog = {}
scheduleLog.liveDate = liveDate;
scheduleLog.ScreenID = screen.id;
scheduleLog.FrameID = frame.FrameID;
if (!errSchedule) {
if (!schedule) {
var tempSchedule = {
LiveDate: liveDate,
Posts: "posts",
Remaining: remain
}
Schedule.create(tempSchedule,
function(err, result) {
if (err) {
output.push({
'Failed': scheduleLog,
'Error': err
});
//callbackFrame(output);
} else {
output.push({
'Created': scheduleLog,
'Success': result
});
//callbackFrame(output);
}
});
} else {
schedule.Remaining--;
schedule.save(function(err, result) {
if (err) {
output.push({
'Failed': scheduleLog,
'Error': err
});
//callbackFrame(output);
} else {
output.push({
'Updated': scheduleLog,
'Success': result
});
//callbackFrame(output);
}
});
} else {
output.push({
'Skipped': scheduleLog,
'Warning': 'Warning: Unable to update. Validation failed. ' + schedule
});
//callbackFrame(output);
}
}
} else {
output.push({
'Skipped': scheduleLog,
'Error': errSchedule
});
//callbackFrame(output);
}
}
);
}
},
function(result) {
if (output)
callback(output);
else
callbackScreen();
});
else {
throw new Error("Invalid Data");
return callbackScreen(output); //should throw an error.
}
},
function(result) {
if (output)
callbackDate(output);
else
callbackDate(output);
});
},
function(result) {
if (output)
callback(output);
else
callback();
});
//callback(output);
}
],
function(result) {
if (output) //also tried result, the outcome is the same.
{
cb(null, output);
} else
cb("Failed!!!");
});
} catch (ex) {
console.log(ex.message);
cb('!Error! ' + ex.message);
}
嵌套的级别令人印象深刻,它可能是时间打破这些代码的功能。这会导致一些错误,比如'if(!schedule)'有2个'else'子句。 – Shanoor