0
 let playlistList = db.get("server").find({"id": msg.guild.id}).get("playlists").value();
    let PlaylistsEmbed = new Discord.MessageEmbed()

playlistList.forEach(playlist =>{
        Youtube.getPlaylist(playlist.url).then(result => {
            PlaylistsEmbed.addField(`"**${playlist.name}**"`, result.title);
        }).catch(()=>{
            Youtube.getVideo(playlist.url).then(video => {  
            PlaylistsEmbed.addField(`"**${playlist.name}**"`, video.title);
            }).catch(()=>{
                msg.channel.send("Invalid URL!");
            })
        })
    });
    msg.channel.send({embed: PlaylistsEmbed});
}

How can I execute the promise before calling msg.channel.send({embed: PlaylistsEmbed});?

PlaylistsEmbed.addField(`"**${playlist.name}**"`, result.title); doesn't seem to work if it's called inside the promise.

I tried putting a new Promise() around it, but I cannot make it work because of the forEach, if I resolve it inside of the forEach, it only adds one entry.

Pedro Dalla
  • 33
  • 1
  • 6
  • 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) – Keith May 05 '20 at 01:11
  • Are you familiar with async/await? – Joel Hager May 05 '20 at 01:11
  • Ok, so I have used async/await, but I'm not being able to wrap my head around this. I add async in front of the function name and put await in front of the forEach, but nothing gets solved. What is the way I should be using it? – Pedro Dalla May 05 '20 at 02:03
  • `async/await` is only a syntactic alternative to `.then()`. It doesn't reall help other than making the code (arguably) easier to read/write. What you are missing is either (a) `Promise.all()` to aggregate the promises generated in the loop, or (b) a `for` loop in which each promise is awaited. – Roamer-1888 May 05 '20 at 02:36

0 Answers0