My current approach involves iterating through a range of dates to find the top song for each date using a for loop. I call a function within this loop to search my database for the top song, and I wrapped it in a promise to prevent it from interrupting the loop. However, this method doesn't seem to be working as expected. Can anyone suggest a better solution to tackle 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);
});
}