【问题标题】:Wrong sequence in printing titles of youTube videos using ytdl-core使用 ytdl-core 打印 YouTube 视频的标题顺序错误
【发布时间】:2019-09-23 09:30:49
【问题描述】:

我有一个不和谐的音乐机器人。我的问题是 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);
                        }
                    }
                });
            })
        }
    }
}

【问题讨论】:

    标签: javascript youtube-api discord.js


    【解决方案1】:

    问题在于,在 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
        });
    }
    

    【讨论】:

    • 嗨@klas,如果这个或任何答案已经解决了您的问题,请点击复选标记考虑accepting it。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做。
    猜你喜欢
    • 2016-12-13
    • 2020-05-05
    • 2021-09-05
    • 2022-01-27
    • 2018-03-09
    • 2015-10-24
    • 2021-08-03
    • 2017-12-17
    • 2021-03-18
    相关资源
    最近更新 更多