0
  1. I am getting some data from spotify api.
  2. Creating an object and saving some values from the returned JSON data
  3. return the object 4.. trying to display the object data.

    /* API ROUTES */
    router.get('/', (req, res) => { 
       // Get artist
       const data = getArtist('Drake');
       if(data) {
        console.log(data.id);
       } else {
         console.log('nothing in data');
       }
    
    
    });
    
    // Get an artist name
    function getArtist(name) {
    
    
     spotify
      .search({ type: 'artist', query: name })
      .then(function(response) {
    
        // Gets Name and Id of the artist
        const data = {
          "id": response.artists.items[1].id,
          "name":  response.artists.items[1].name
        }
    
        return data;
      })
      .catch(function(err) {
        console.log(err);
      });
    }
    

Displays the error: nothing in data.

Coming from JAVA not sure what I am doing wrong in Javascript. Ideas? Is there a better way?

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Shaz
  • 1,443
  • 1
  • 27
  • 67
  • 2
    Spotify.search is an async call. By the time the call returns successfully, your code has already evaluated `data` which will always be `undefined`. You can observe the `data` property or execute your code in the success callback. – AmmoPT Sep 04 '18 at 11:45
  • Thank you! I get it now @AmmoPT – Shaz Sep 04 '18 at 11:58

1 Answers1

1
Try This:   

    router.get('/', (req, res) => { 
       // Get artist
       getArtist('Drake').then( (response) => {
         if(response) {
            const data = {
               "id": response.artists.items[1].id,
               "name":  response.artists.items[1].name
            }
            console.log(data.id);
         } else {
             console.log('nothing in data');
         }
       });
   });  

    // Get an artist name
    function getArtist(name) {
        return spotify.search({ type: 'artist', query: name });
    }
Ritesh Waghela
  • 3,474
  • 2
  • 19
  • 25