0

I have a function and a loop:

var songs = Musics.searchSongs(query).then(function(rs) {
   return rs;
  });
  for (var i = 0; i < songs.length; i++) {
   console.log(songs[i]);
  }

Now I want to run the loop with the result that taken from after executing the function. How can I do that?

Ben
  • 215
  • 1
  • 2
  • 8

1 Answers1

1

You cannot return from an asynchronous call. You can, however, pass in a callback function to an asynchronous call, and pass the result of the call to that callback function.

So, in your case, you could create a function that receives an array of songs, and loops through each song, logging each to the console. You would then pass that function as a parameter to your asynchronous call.

function callback(songs) {
    for (var i = 0; i < songs.length; i++) {
        console.log(songs[i]);
    }
};

Musics.searchSongs(query, callback).then(function(rs) {
    callback(rs);
};
artis3n
  • 810
  • 2
  • 12
  • 23