Search code examples
javascriptbotsunhandled-promise-rejection

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


I was following a tutorial YT here's the link https://www.youtube.com/watch?v=7rU_KyudGBY&t=726s to create a discord bot. But I have an error that I can't figure out how to fix. It says "cannot read the property of q". The only q I have in my code is in the getQuote function. What I'm trying to do is when I type $inspire, the bot will give an inspiring quote. But when I do that it gives the error "cannot read the property of q" and also "

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)

its a bit outdated(it was made on March 8, 2021). I coded this in repl. Any ideas of how it would work? Thanks in advance


Solution

  • unhandledPromiseRejection errors occur when you don't "handle" the case where Promises are rejected. This means that you should look at your code to find implementations of Promises, and make sure you handle the failure case – with Promises, that usually means implementing a catch or a finally case in the chain.

    Looking at your code, it's most probably because you're not catching potential errors in your fetch call.

    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 :)
        });
    }