0

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);
KoenZelf
  • 1
  • 1
  • 1
    `years()` is a asynchronous function so it does not wait for the response and execute the code `console.log("uniqueYears is = " + uniqueYears);` so you get `undefined` as output. – Ankit Agarwal Jul 10 '18 at 14:07
  • thanks @AnkitAgarwal, I found that post as well. But I've been unable to apply the information in it to my case. Would really appreciate any pointers you could have. – KoenZelf Jul 10 '18 at 15:11
  • nevermind, I've got it to work. thanks for looking into it – KoenZelf Jul 10 '18 at 19:37

0 Answers0