0

Below I am trying to pull songs from SoundCloud (based on an array of genres that I pass through), put these songs into an array, return that array, and then flatten that array (since the returned array is an array of arrays).

var genreArray = ['pop', 'hip-hop', 'alternative'];

var each = function (collection, callback) {
    if (Array.isArray(collection)) {
      for (var i=0; i<collection.length; i++) {
        callback(collection[i]);
      }
    } else {
      for (var key in collection) {
        callback(collection[key]);
      }
    }
};

var flatten = function (array) {
    var results = [];
    each (array, function(item) {
        if(Array.isArray(item)) {
            results = results.concat(flatten(item));
        } else {
            results.push(item);
        }
    })
    return results;
};

var getSongs = function (genreSelection) {
    var mySongArray = [];
    each (genreSelection, function (genre) { 
        SC.get('/tracks', { tags: genre }).then(function(tracks) {
            mySongArray.push(tracks);
        });
    });
    return mySongArray;
};

When I include the following, mySongs correctly returns the array of arrays that it should, but myFlattenedSongs returns an empty array. It's weird because when I take the line with myFlattened songs out of my code and then go into the console and manually put it in, it flattens the array of arrays as it should. Any thoughts on what might be going wrong here?

var mySongs = getSongs(genreArray);
var myFlattenedSongs = flatten(mySongs);
Adam Azad
  • 11,171
  • 5
  • 29
  • 70
Kim Curran
  • 25
  • 2

1 Answers1

0

GetSongs is pushing tracks in an ajax success resolver which means that the return statement fires before the "then" function executes.

var getSongs = function (genreSelection) {
    var mySongArray = [];
    each (genreSelection, function (genre) { 
        //This fires after the api fetches the data
        SC.get('/tracks', { tags: genre }).then(function(tracks) {
            mySongArray.push(tracks);
        });
    });

   // this fires before the api call
    return mySongArray;
};
Bhargav Ponnapalli
  • 9,224
  • 7
  • 36
  • 45