1

我正在关注 YT 教程,这里是链接https://www.youtube.com/watch?v=7rU_KyudGBY&t=726s来创建一个不和谐的机器人。但是我有一个错误,我不知道如何解决。它说“无法读取 q 的属性”。我的代码中唯一的 q 在 getQuote 函数中。我想要做的是,当我输入 $inspire 时,机器人会给出一个鼓舞人心的报价。但是当我这样做时,它会给出错误“无法读取 q 的属性”以及“

const Discord = require("discord.js")

const fetch = require("node-fetch")

const client = new Discord.Client()

const mySecret = process.env['TOKEN']

function getQuote() {
  return fetch("https://zenquotes.io/api/random")
.then(res => {
  return res.json
})
.then(data => {
  return data[0]["q"] + " -" + data[0]["a"]
})
}

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`)
})

client.on("message", msg => {
  if(msg.content === "ping")  {
    msg.reply("pong")
  }
})

client.on("message", msg => {
  if(msg.author.bot)return

  if(msg.content === "$inspire") {
    getQuote().then(quote => msg.channel.send(quote))
  }
})

client.login(process.env.TOKEN)

它有点过时(它是在 2021 年 3 月 8 日制作的)。我在 repl 中对此进行了编码。关于它如何工作的任何想法?提前致谢

4

1 回答 1

1

unhandledPromiseRejection当您不“处理” Promise 被拒绝的情况时,就会发生错误。这意味着你应该查看你的代码以找到 Promise 的实现,并确保你处理了失败的情况——对于 Promises,这通常意味着在链中实现一个catch或一个案例。finally

查看您的代码,很可能是因为您没有在调用中发现catch潜在的错误。fetch

function getQuote() {
  return fetch("https://zenquotes.io/api/random")
    .then(res => {
      return res.json() // <- careful here too.. `json()` is a method.
    })
    .then(data => {
      return data[0]["q"] + " -" + data[0]["a"]
    })
    
    // +
    .catch((error) => {
      // Catch errors :)
    });
}
于 2021-06-17T17:42:59.763 回答