无法通过 DiscordJS 中的不同范围传递变量

Cannot Pass Variables Through Different Scopes in DiscordJS

好吧,我的问题是,在第一组 console.log(streamXXXX) 中,XXXX 是各种变量,当我读取它们的值时,它们都按应有的方式读取,而在第二组中,它们读取为不明确的。这是范围问题吗?也许是异步问题?每次发出网络请求时,我都尝试添加等待,但似乎没有任何效果,最有趣的部分之一是没有错误?

无论如何,下面列出了我的代码,以及 link 以使用我创建的示例机器人在 Repl 中对其进行测试。下面是上述程序 运行 所需的库列表。谢谢!

if (!message.member.voiceChannel) return message.channel.send(`You do realize you have to be in a voice channel to do that, right ${message.author.username}?`)

if (!message.member.voiceConnection) message.member.voiceChannel.join().then(async connection => {

    let streamURL = args.slice(1).join(" ")
    let streamTitle = "";
    let streamThumb = "";
    let streamAuth = "";
    let streamAuthThumb = "";

    if (streamURL.includes("https://www.youtube.com") || streamURL.includes("https://youtu.be/") && !streamURL.includes(' ')) {
        youtube.getVideo(streamURL)
            .then(async results => {
                let {
                    body
                } = await snekfetch.get(`https://www.googleapis.com/youtube/v3/channels?part=snippet&id=${results.channel.id}&fields=items%2Fsnippet%2Fthumbnails&key=${ytapikey}`).query({
                    limit: 800
                })

                streamTitle = results.title
                streamThumb = results.thumbnails.medium.url
                streamAuth = results.channel.title
                streamAuthThumb = body.items[0].snippet.thumbnails.medium.url

                console.log(streamURL)
                console.log(streamTitle)
                console.log(streamThumb)
                console.log(streamAuth)
                console.log(streamAuthThumb)
            })
            .catch(console.error)
    } else if (!streamURL.includes("https://www.youtube.com") || !streamURL.includes("https://youtu.be/")) {
        youtube.searchVideos(streamURL)
            .then(async results => {
                let {
                    body
                } = await snekfetch.get(`https://www.googleapis.com/youtube/v3/channels?part=snippet&id=${results[0].channel.id}&fields=items%2Fsnippet%2Fthumbnails&key=${ytapikey}`).query({
                    limit: 800
                })

                streamURL = results[0].url
                streamTitle = results[0].title
                streamThumb = results[0].thumbnails.default.medium.url
                streamAuth = results[0].channel.title
                streamAuthThumb = body.items[0].snippet.thumbnails.medium.url
            }).catch(console.error)
    } else {
        return message.reply("I can only play videos from YouTube (#NotSponsored).")
    }

    console.log(streamURL)
    console.log(streamTitle)
    console.log(streamThumb)
    console.log(streamAuth)
    console.log(streamAuthThumb)

    const stream = ytdl(streamURL, {
        filter: 'audioonly'
    })
    const dispatcher = connection.playStream(stream)
    dispatcher.on("end", end => {
        return
    })

    let musicEmbed = new Discord.RichEmbed()
        .setAuthor(streamAuth, streamAuthThumb)
        .setTitle(`Now Playing: ${streamTitle}`)
        .setImage(streamThumb)
        .setColor(embedRed)
        .setFooter(`${streamAuth} - ${streamTitle} (${streamURL}`)

    await message.channel.send(musicEmbed)
})

Link to test out the program on a sample bot I made

您需要测试的模块:

discord.js
simple-youtube-api
node-opus
ffmpeg
ffbinaries
ffmpeg-binaries
opusscript
snekfetch
node-fetch
ytdl-core

再次感谢!

您的输出是 undefined 的原因是由于 promise 的工作方式以及您构建代码的方式:

let streamTitle = "";

// 1. Promise created
youtube.getVideo(streamURL)
  // 2. Promise still pending, skip for now
  .then(async results => {
    // 4. Promise fulfilled
    console.log(results.title); // 5. Logged actual title
});

console.log(streamTitle); // 3. Logged ""

您已经为您的 snekfetch 请求找到了正确的方法,只需要将它也应用到 YT 请求中:

let streamTitle = "";

const results = await youtube.getVideo(streamURL);

streamTitle = results.title;

console.log(streamTitle); // Desired output