如何修复 repl.it 中未处理的承诺拒绝。我说的错误 "cannot read the property of q"

How to fix an unhandledpromiserejection in repl.it. The error I had said "cannot read the property of q"

我正在按照 YT 教程 link https://www.youtube.com/watch?v=7rU_KyudGBY&t=726s 创建一个不和谐的机器人。但是我有一个错误,我不知道如何修复。它说“无法读取 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 中编码了这个。关于它将如何工作的任何想法?提前致谢

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

查看您的代码,很可能是,因为您没有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 :)
    });
}