darthbatman / billboard-top-100

:chart_with_upwards_trend: Node.js API to retrieve the top songs, albums, and artists from Billboard's charts
MIT License
97 stars 30 forks source link

Help needed: How to wait for getChart method to execute its callback? #49

Closed mizanxali closed 2 years ago

mizanxali commented 3 years ago

Hi! I have been using this API for a personal project and I'm kinda stuck in this situation. Consider the following case

//initialize an empty array
const songTitles = []

//make API call
getChart('hot-100', (err, chart) => {
    if (err) console.log(err);

    //push titles of all songs on the chart to songTitles array
    chart.songs.map(song => {
      songTitles.push(song.title)
    })
});

//log the array
console.log(songs);

An empty array is logged upon executing this piece of code. So, basically, how do I wait for the callback to mutate the array before it is logged to the console? Any help would be greatly appreciated!

Noicerino commented 3 years ago

I had the same issue as you earlier, in this instance your line of code "console.log(songs)" is executing before everything else hence why it turns out to be empty. Sadly I do not think there is a way to log it outside of the getChart function, so you might need to run all your code in there

darthbatman commented 2 years ago

Closing as this is not an issue with billboard-top-100.