0
var songs = [];

request.get(getSongs, function(error, response, body){
  append(songs,body);
});

function append(arr, data){
  for (let j = 0; j < data.items.length; j++) {
    console.log(data.items[j].track.name);
    arr.push(songs,data.items[j].track.name);
  }
}



console.log(songs); //outputs '[]'

I've google a lot and I'm not sure what I'm doing wrong.

For some context, request.get() returns between 1 and 20 objects, and I'd like to add an attribute (or more) of all of them to the array 'songs'. They console.log() correctly and their positions are correct, but when I log the array, it appears to be empty.

What am I doing wrong? Thanks for the help.

winhowes
  • 7,845
  • 5
  • 28
  • 39
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Andy Taton Aug 22 '18 at 03:09
  • What is request? Is that a library? or nodes http class – ngearing Aug 22 '18 at 03:31
  • A request calls spotify's API and passes in this case a certain number and order of songs that have already been specified. The data returns properly, and I have no problem console.logging it, I just can't figure out how to store it. – Ethan DeGuire Aug 22 '18 at 16:24

1 Answers1

0

The issue you have here is that you're logging the array synchronously. Currently, your program currently runs as follows:

  1. Defines an empty array
  2. Kicks off a request to get songs
  3. Defines your append function
  4. logs the empty array
  5. Gets back the songs
  6. Populates the array with the songs.

If you console.log after your append call you'll see you have all the songs in your array.

winhowes
  • 7,845
  • 5
  • 28
  • 39
  • I've done this, and even used a DOM button far after the array should be filled, and it still shows up as empty. I'm not sure why its not filling the array. – Ethan DeGuire Aug 22 '18 at 16:23