Javascript node.js中的foreach异步函数
我想迭代每个学生,然后执行两个查询,这两个查询的执行应该是同步的,第一个是同步的,因为第二个查询依赖于第一个查询 我已经编写了一些代码,但似乎根本不起作用:Javascript node.js中的foreach异步函数,javascript,node.js,asynchronous,mongoose,Javascript,Node.js,Asynchronous,Mongoose,我想迭代每个学生,然后执行两个查询,这两个查询的执行应该是同步的,第一个是同步的,因为第二个查询依赖于第一个查询 我已经编写了一些代码,但似乎根本不起作用: Student.find({ status: 'student' }) .populate('student') .exec(function (err, students) { if (err) { return res.status(400).send({
Student.find({ status: 'student' })
.populate('student')
.exec(function (err, students) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
}
_.forEach(students, function (student) {
async.waterfall(
[
function (callback) {
console.log('first ' + student.firstName);
Student.find({ "_id": student.id }, callback);
},
function (student, callback) {
console.log('second '+ student[0].firstName);
WorksnapsTimeEntry.find({
"student": {
"$in": student.map(function (el) {
return el._id
})
}
}, callback);
}
],
function (err, results) {
if (err) {
// do something
} else {
// results are the matching entries
console.log('third');
var totalMinutes = 0;
var totalAvgLevelActivity = 0;
var counter = 0;
_.forEach(results, function (item) {
_.forEach(item.timeEntries, function (item) {
if (item.duration_in_minutes) {
totalMinutes = totalMinutes + parseFloat(item.duration_in_minutes[0]);
}
if (item.activity_level) {
totalAvgLevelActivity = totalAvgLevelActivity + parseFloat(item.activity_level[0]);
counter++;
}
});
});
var obj = {};
obj.studentId = 'test';
obj.firstName = 'test';
obj.lastName = 'test';
obj.municipality = 'test';
obj.totalMinutes = totalMinutes;
obj.totalAvgLevelActivity = totalAvgLevelActivity / counter;
arrayReports.push(obj);
// console.log('not yet finished.');
}
}
);
});
res.json(arrayReports);
console.log('finished.');
任何人都知道如何在Node中实现这一点。js
mongoose
被承诺,您不必使用async
来处理流,也不必使用lodash来处理简单的forEach。而且您的“按id查找”请求无效,您已经有了一个学生
对象:
Student.find({ status: 'student' })
// .populate('student') // why this?
.then(function (students) {
// build an array of promises
var promises = students.map(function (student) {
return WorksnapsTimeEntry.find({
"student": student._id;
});
});
// return a promise to continue the chain
return Promise.all(promises);
}).then(function(results) {
// results are the matching entries
console.log('third');
var totalMinutes = 0;
var totalAvgLevelActivity = 0;
var counter = 0;
_.forEach(results, function (item) {
_.forEach(item.timeEntries, function (item) {
if (item.duration_in_minutes) {
totalMinutes = totalMinutes + parseFloat(item.duration_in_minutes[0]);
}
if (item.activity_level) {
totalAvgLevelActivity = totalAvgLevelActivity + parseFloat(item.activity_level[0]);
counter++;
}
});
});
var obj = {};
obj.studentId = 'test';
obj.firstName = 'test';
obj.lastName = 'test';
obj.municipality = 'test';
obj.totalMinutes = totalMinutes;
obj.totalAvgLevelActivity = totalAvgLevelActivity / counter;
arrayReports.push(obj);
// console.log('not yet finished.');
res.json(arrayReports);
console.log('finished.');
}).catch(function(err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
});
mongoose
被推荐,您不必使用async
来处理流程,也不必使用lodash来处理简单的forEach。而且您的“按id查找”请求无效,您已经有了一个学生
对象:
Student.find({ status: 'student' })
// .populate('student') // why this?
.then(function (students) {
// build an array of promises
var promises = students.map(function (student) {
return WorksnapsTimeEntry.find({
"student": student._id;
});
});
// return a promise to continue the chain
return Promise.all(promises);
}).then(function(results) {
// results are the matching entries
console.log('third');
var totalMinutes = 0;
var totalAvgLevelActivity = 0;
var counter = 0;
_.forEach(results, function (item) {
_.forEach(item.timeEntries, function (item) {
if (item.duration_in_minutes) {
totalMinutes = totalMinutes + parseFloat(item.duration_in_minutes[0]);
}
if (item.activity_level) {
totalAvgLevelActivity = totalAvgLevelActivity + parseFloat(item.activity_level[0]);
counter++;
}
});
});
var obj = {};
obj.studentId = 'test';
obj.firstName = 'test';
obj.lastName = 'test';
obj.municipality = 'test';
obj.totalMinutes = totalMinutes;
obj.totalAvgLevelActivity = totalAvgLevelActivity / counter;
arrayReports.push(obj);
// console.log('not yet finished.');
res.json(arrayReports);
console.log('finished.');
}).catch(function(err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
});
你们有什么输出吗?是的,我可以看到学生的名字被打印出来,但我不确定他们是否以这种方式打印,第一个学生必须完成所有事情,直到第二个学生开始。。。此外,res.json(arrayReports)总是空的,因为它当然是在foreach中的查询完成之前执行的,我有没有办法等到所有查询完成后再执行res.json()。我猜您使用的是
async.fallet
错误。从每个任务函数中,您需要使用合适的参数调用下一个函数,您是否得到任何输出?是的,我可以看到打印的是学生的名字,但我不确定他们是否以这样的方式打印,第一个学生必须完成所有工作,直到第二个学生开始。。。此外,res.json(arrayReports)总是空的,因为它当然是在foreach中的查询完成之前执行的,我有没有办法等到所有查询完成后再执行res.json()。我猜您使用的是async.fallet
错误。从每个任务函数中,您需要使用合适的参数调用下一个函数some,nice,clean,最重要的是,可工作:)thnx aware,nice,clean,最重要的是,可工作:)thnx