使用 ytdl-core 打印 YouTube 视频标题的顺序错误
Wrong sequence in printing titles of youTube videos using ytdl-core
我有一个不和谐的音乐机器人。我的问题是 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);
}
}
});
})
}
}
}
问题是在 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
});
}
我有一个不和谐的音乐机器人。我的问题是 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);
}
}
});
})
}
}
}
问题是在 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
});
}