1
votes

I have a discord music bot. My problem is wrong sequence in printing titles of youTube videos. When I'm going to send results into the text channel I see a random sending titles, not that what I expected.

I've tried to use async/await functions, but it still doesn't work.

function queueNow(message) {
    let arr = queueArr; //array with urls
    if(arr !== undefined && arr.length !== 0) {
        let mes = "```Elm";
        let counterPlaylist = 0;
        if(arr.length != 0) {
            let flag = true;
            arr.forEach(composition => {
                ytdl.getInfo(composition, function(err, info) {
                    if(err === null) {
                        if(info === undefined) {
                            flag = false;
                        }
                        if(flag) {
                            counterPlaylist++;
                            mes += "\n" + counterPlaylist + ") " + info.title;
                        }
                        if(counterPlaylist === arr.length) {
                            mes += "\n```"
                            message.channel.send(mes);
                        }
                    }
                });
            })
        }
    }
}
1

1 Answers

0
votes

The problem is that making async calls inside a forEach does not necessarily respect the order in which they have been made.

Here is a possible workaround with some refactoring using Promise.all, which preserves the order of the calls:

function queueNow(message, arr) {
  if (!arr || !arr.length) return;
  Promise.all(arr.map(composition => ytdl.getInfo(composition)))
    .then(infos => {
      const mes =
        "```Elm" +
        infos.map((info, index) => `\n${index + 1}) ${info.title}`).join("") +
        "\n```";
      message.channel.send(mes);
    })
    .catch(err => {
      console.log(err);
      // Do something with the error
    });
}