简体   繁体   English

node.js中的foreach异步功能

[英]foreach async function in node.js

I would like to iterate thru each of the students and then excecute two query which the execution of these two queries should be sync, first one first then since the second query depends on the first. 我想遍历每个学生,然后执行两个查询,这两个查询的执行应同步,首先是第一个,然后是第二个查询,因为这取决于第一个。

I have written some code but it does not seem working at all: 我已经写了一些代码,但似乎根本不起作用:

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.');

Anyone has an idea how do I achieve this thing in Node.js 任何人都知道如何在Node.js中实现这一目标

mongoose is promisified, you don't have to use async to handle the flow nor lodash for a simple forEach. mongoose是应许的,您不必使用async来处理流,也不必使用lodash来实现简单的forEach。 And your find by _id request is useless, you already have a Student object: 并且您通过_id请求查找是无用的,您已经有一个Student对象:

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)
        });
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM