0

I am making a discord bot that will fetch a quotes from api and then return it as a discord reply code ->

const { SlashCommandBuilder } = require("@discordjs/builders");


const fetch = async (...args) =>
import("node-fetch")
  .then(({ default: fetch }) =>
    fetch("https://animechan.vercel.app/api/random"))
  .then((res) => res = JSON.stringify(res))
  .then((res) => {return res});


async function main(){
data = await fetch()
console.log(data);
return data
}

quote= main()

console.log(quote)
quote= JSON.stringify(quote);
console.log(typeof(quote))
console.log(quote)

module.exports = {
  data: new SlashCommandBuilder()
    .setName("ani-quote")
    .setDescription("Gives a random anime quote"),
  async execute(interaction) {
      const sent = await interaction.reply({
        content: quote,
      });
  },
};

I am these the problem

  1. the variable "quote" is a promise that is pending and then when I try quote= JSON.stringify(quote); it turns the promise into string with {} is there anyway to fix this? so that the stringify is run after the promise is full filled

  2. the quote is regenerated only when the bot starts

  • 2
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – about14sheep Sep 25 '22 at 14:07
  • Main returns a promise so you have to wait for its resolution before accessing the data it returns. `main().then(quote=>console.log(quote))` – Peterrabbit Sep 25 '22 at 14:14
  • Shouldn't you just call `fetch()` in *every* `execute` call, not just once at startup in `main`? – Bergi Sep 25 '22 at 14:18
  • Btw, `JSON.stringify(res)` doesn't work as you expect either, what you want is `.then(res => res.text())` – Bergi Sep 25 '22 at 14:19

0 Answers0