簡體   English   中英

node.js中的foreach異步功能

[英]foreach async function in node.js

我想遍歷每個學生,然后執行兩個查詢,這兩個查詢的執行應同步,首先是第一個,然后是第二個查詢,因為這取決於第一個。

我已經寫了一些代碼,但似乎根本不起作用:

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對象:

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