I have the following for my Discord.js bot which, when the command $music queue
is executed, sends a message in the Discord channel with the next titles to play:
First, I have loop which loops through all the elements from the queue array (which are ALL youtube links):
// Loop through each links and get their info.title with ytdl. Then, store it in queue.
conf.settings[server.id].queue.forEach((link, i) => {
ytdl.getInfo(link, function(err, info){
queue += `${i + 1}. ${info.title}\n`;
});
});
message.channel.send(queue);
The message that is sent is simply:
Music Queue:
when it should be sending:
Music Queue:
1. songTitle
2. songTitle
Now, I do know this has to do with I think ytdl.getInfo() being an asynchronous function (yet not entirely sure). I've been looking around for info on this on many websites, but the only cases where the code executed in the callback function of ytdl produces results is when using console.log, which by the way also works for me, but that's not what I want. (The fact that it only works with console.log is what I'm basing my idea of it being an async function)
Instead of logging it into the console, I want to actually store it in the variable 'queue' as shown in the code. I know I need something to delay the rest and make it wait for the ytdl function to be done and THEN proceed to the rest of the code, but I simply ran out of options. I tried callbacks, promises and gens (but I was not familiar with promises and gens until then so I might have done it wrong and callbacks can get messy so maybe I messed up there too). I haven't tried timeouts, but I don't think they're really good practice for this kind of case, especially considering this is a bot that will handle commands coming from multiple servers.
Does anyone know a way I could store the info from ytdl.getInfo() in a variable?