I've got a bunch of Video objects in a database, each with a year: attribute. I'm trying to create a function that will return an array of all unique years, in order. The unique years and the correct order part works like a charm. But the array that is returned is always undefined.
I've spent the afternoon going over callback related questions and answers but I think I'm missing a key part of it. How should I call years(), to ensure var uniqueYears is filled correctly? Hope someone is willing to help out.
My code is as follows:
var yearList = [];
function years(){
Video.find({}, function(err, allVideos){
sortByKey(allVideos, "year").reverse();
var currentYear = allVideos[0].year;
yearList.push(currentYear);
for(i=0; i<allVideos.length; i++) {
if(allVideos[i].year < currentYear){
currentYear = allVideos[i].year;
yearList.push(currentYear)
}
}
console.log("yearList after forloop is " + yearList)
return yearList
})
}
var uniqueYears = years();
console.log("uniqueYears is = " + uniqueYears);