0

I have a route in my API. When you apply to this router, the last 7 days are generated and on each day of the day the elements are extracted from the database. But apparently because of asynchrony, the sample does not work out as it should.

apiRoutes.get('/costs/chart', function (req, res) {

    var currentDay = moment().format('L');
    var currentWeekDays = [];

    for (var i = 0; i < 7; i++) {
        var day = {
            date: (function () {
                var date = moment().add(-[i], 'd');
                return moment(date).format('L');
            })(),
            costs: []
        };

        Cost.find({formatDate: day.date}, function (err, costs) {
            if (costs.length > 0) {
                console.log(costs);
                day['costs'] = costs;
            }
        });

        currentWeekDays.push(day);
    }

    var result = {
        content: {
            currentDay: currentDay,
            currentWeekDays: currentWeekDays
        }
    };

    res.json(result);
});
Сruel Man
  • 63
  • 1
  • 8
  • So you know you can actually just query for a "range of dates" and simply do this without the loop as well. So adding another answer to look at for that one. – Neil Lunn Jul 22 '17 at 09:06
  • But I need to then select for each date from the database and only after the end of the cycle to give the result ... I have not quite understood how to implement it. – Сruel Man Jul 22 '17 at 09:27
  • Read the linked answers and learn. Learning simply how to to apply `async/await` is the path of least resistance here. But you should also understand the concepts. Particularly that there is absolutely no need for async calls in a loop for the results you want. It should actually be one call, and post processing the results. All the linked answers have things you can learn from – Neil Lunn Jul 22 '17 at 09:30
  • Good. I will study. Thanks for the help. Have a nice day. – Сruel Man Jul 22 '17 at 09:37

0 Answers0