0

When I use this code the musicData comes out undefined even though I set it to metaData. Also, I know metadata has info in it.

let musicData;
for(i = 0; i < queue.length; i++) {
  queueString += i + 1 + ": `" + queue[i] + "`\n";
  mm.parseFile(config.MUSIC_DIR + queue[i]).then( metadata => {musicData = metadata;});
  console.log(musicData);
}
mnist
  • 6,571
  • 1
  • 18
  • 41
  • Is this inside an async function? If so, you can await `mm.parseFile`. Otherwise, you cannot assign the result to `musicData` like this. – evolutionxbox Nov 01 '20 at 18:42
  • 1
    Does this answer your question? [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) – evolutionxbox Nov 01 '20 at 18:42

2 Answers2

1

If you try to return musicData variable from for loop it always shows undefined. So Good to serch how to return data from for loop. if else try to use musicData variable inside the for loop.

like that

for(i = 0; i < queue.length; i++) 
{
   let musicData;
   queueString += i + 1 + ": `" + queue[i] + "`\n";
   mm.parseFile(config.MUSIC_DIR + queue[i]).then( metadata => {musicData = metadata;});
   console.log(musicData);
}
  • Why does this resolve the issue? – evolutionxbox Nov 01 '20 at 19:03
  • The reason is because the for loop has an exit point controlled by a boolean variable. It doesn’t need a return statement, which is only to be used in a body of a function. –  Nov 01 '20 at 19:23
  • The reason I ask is because `mm.parseFile` is a promise so its `then` could be run after `console.log(musicData)`. So I'm confused as to what resolves the issue. --- (This is why the question has been marked as a duplicate) – evolutionxbox Nov 01 '20 at 19:25
0

Try for..of loop with await in it

let musicData;
let index = 0;
(async () => {
  for (const element of queue) {
    index++;
    queueString += index + ": `" + element + "`\n";
    await mm
      .parseFile(config.MUSIC_DIR + element)
      .then((metadata) => (musicData = metadata));
    console.log(musicData);
  }
})();
Parse Shyam
  • 366
  • 2
  • 14