I'm building an Discord music bot and I need to generate one object with this function. Problem is that the function returns too early and the object is not build entirely. Loop in function only finishes after function is exited.
Function fetchVideoInfo() executes passed callback in .then()function of promise that it retuens, as provided on image. However i can't edit it because it's a part of a module. What I think that is a problem is that even tho i awaiting for fetchVideoInfo() to complete,it still goes on because of how it is written, executing callback after internal promise. Ill provide the part of it's code that returns the actual promise and calls the callback function. What I've tried is to have my function return promise but it did not work for what I think is the same issue, function ends before the callback, that i have to await. I've also tried wrapping callback function in another one and then passing it, while awaiting initial function, but it also didn't do well.
https://i.sstatic.net/6Qsm7.jpg This is link to image of the return value in that module("youtube-info"). The whole module is actually the fetchVideoInfo() function
async function generatePlayList(queue) {
const date = new Date();
let embed = new Discord.RichEmbed();
embed
.setTitle("Playlist")
.setColor("#25473A")
.setDescription("Music currently in playlist!")
.setFooter("Time ")
.setTimestamp(date);
for await (let id of queue)
fetchVideoInfo(id, (Null, info) => {
const { duration, title, url } = info;
const seconds = duration % 60;
const minutes = Math.trunc(duration / 60);
embed.addField(`[${title}](${url})`, `Duration ${minutes}:${seconds}`);
console.log(embed.fields);
});
console.log(embed.fields);
return embed;
}
What happens now is that the function returns first resulting in embed object unmodified, even though there is for - await - of loop(It is new ES2018 syntax) before it. It should first complete the for - of loop and then return