Skip to content Skip to sidebar Skip to footer

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 d

Solution 1:

mongoose is promisified, you don't have to use async to handle the flow nor lodash for a simple forEach. And your find by _id request is useless, you already have a Student object:

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

Post a Comment for "Foreach Async Function In Node.js"