首页 > 解决方案 > 使用 ytdl-core 打印 YouTube 视频的标题顺序错误

问题描述

我有一个不和谐的音乐机器人。我的问题是 YouTube 视频标题的打印顺序错误。当我将结果发送到文本通道时,我看到一个随机发送的标题,这不是我所期望的。

我尝试使用 async/await 函数,但它仍然不起作用。

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);
                        }
                    }
                });
            })
        }
    }
}

标签: javascriptyoutube-apidiscord.js

解决方案


问题是在 a 内部进行异步调用forEach不一定尊重它们的执行顺序。

这是一个可能的解决方法,使用 进行一些重构Promise.all,它保留了调用的顺序:

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
    });
}

推荐阅读