0

I have the following Javascript code which is interacting with the Last.Fm API.

let textarea = document.getElementById('username_entry').addEventListener('keydown', (e) => {
    if (event.key === 'Enter') {
        event.preventDefault(); // prevents the submit on Enter

        // ---- Attributes ----
        const username = document.getElementById('username_entry').value;
        const api_key = MY_API_KEY_HERE;
        const url = "http://ws.audioscrobbler.com/2.0/?method=user.gettopartists&user=" + username + "&api_key=" + api_key +"&format=json";
        const users_top_artists = [] // List to hold the users top 50 artists

        // ---- Fetch the Json data ----
        fetch(url).then(function(resp) {
            return resp.json();
        }).then(function(data){

            // ---- Append each of the users top 50 artists to a list ----
            for(let artist of data.topartists.artist){
                users_top_artists.push(artist.name);
            }
        });

        // ---- Iterate through each of the users top listens and print out similar artists ----
        users_top_artists.forEach(function(entry){
            console.log(entry); // logging to console simply for testing. There will be a more in-depth action completed here
        });

      }
});

If I replace the forEach loop and instead print the entire list to console, all of the data is in the list. For some reason though, I can't seem to figure out how to iterate over the loop and print each item in the list. The console remains blank.

Any suggestions as to what I am doing wrong here?

For reference, the section that I am having difficulty with is this:

 // ---- Iterate through each of the users top listens and print out similar artists ----
        users_top_artists.forEach(function(entry){
            console.log(entry); // logging to console simply for testing. There will be a more in-depth action completed here
        });

Thank you very much for your time and if there is anything I can add or adjust for clarity, please don't hesitate to ask.

DougM
  • 920
  • 1
  • 9
  • 21
  • 1
    your `.forEach` is running before your array gets populated (as your array is populated with data asynchronously). You'll need to work with the data inside of your `.then()` callback – Nick Parsons Feb 24 '20 at 03:56
  • 1
    @NickParsons oh, amazing. Thank you so much much. – DougM Feb 24 '20 at 03:57

0 Answers0