javascript - 使用 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);
}
}
});
})
}
}
}
解决方案
问题是在 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
});
}
推荐阅读
- docker - 为什么`chmod`会导致`docker build`耗尽磁盘空间
- vba - 在单独的文件中拆分 Access 数据库
- regex - 在 perl 中只打印匹配的字符
- prometheus - 如何划分两个 Prometheus 计数器
- javascript - 使用 WebRTC 时不立即显示视频
- xamarin.forms - FreshMVVM - 从不继承 FreshBasePageModel 的子 ContentView 打开页面的最佳方式
- windows - 如何为没有任何依赖关系的 Windows EXE 文件从头开始创建 Dockerfile?
- oracle - 没有通过递归过程得到正确的输出
- c# - 如何在我的 xamarin andriod 中将 TextView.Text 保存为文本文件
- java - 如何在 IntelliJ IDEA 中创建用于运行套件的 JUnit 运行/调试配置