I am trying to iterate through a range of dates to return the top song for each date. So I have a for loop. Within this for loop a function is called to look through my database for the top song. Therefore I wrapped it in a promise in order that it would hold up the for loop, but this approach does not seem to work either. Can someone explain a better approach to solve this issue.
app.post('/getDate', function (req, res) {
this.tracks = [];
let until = new Date(req.body.dateToOutput);
for (var d = new Date(req.body.dateFromOutput); d <= until; d.setDate(d.getDate() + 1)) {
date = d.toLocaleDateString('en-US', { timeZone: 'UTC' });
console.log('date', date);
new Promise(function (resolve, reject) {
getDate(date).then(() => {
resolve();
})
});
}
console.log(this.tracks);
});
function getDate(date) {
return new Promise(function (resolve, reject) {
Track.find({ Date: date }, function (err, track) {
if (!err) {
console.log(track);
this.tracks.push(track);
resolve();
}
else {
reject();
}
}).sort({ Streams: -1 }).limit(1);
});
}