私は不和の音楽ボットを持っています。私の問題は、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
});
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加