Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

249
Visualizações
I am trying to use the return value that I get in this .then() function. I don't know how to fix it

I am trying to use the return value that I get in this .then() function in my discord bot function to send a message of any stock price that they enter. When I run the function in the discord function it says 'undefined' but the correct price is being logged in the .then() function. Please Help!

const alpha = require("alphavantage")({ key: "KEY" });

const { Client, Intents } = require("discord.js");
const Discord = require("discord.js");

const client = new Client({
  intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES],
});

const tickers = ["CVE", "SU", "AAPL", "TSLA", "CNQ", "FUBO", "FB"];
const prefix = ".";

client.once("ready", () => {
  console.log("Bot is Ready!");
});

getInput();

function getInput() {
  client.on("message", (msg) => {
    if (!msg.content.startsWith(prefix) || msg.author.bot) return;

  const args = msg.content.slice(prefix.length).trim().split(" ");
  const command = args.shift().toLowerCase();

  if (command === "list") {
    msg.channel.send(tickers.join(", "));
  } else if (command == "add") {
    tickers.push(args[0]);
  } else if (command == "price") {
    console.log(getStockPrices(args[0]));
  }
  });
client.login("KEY");
}

function getStockPrices(stock) {
 let prices = [];

 alpha
   .experimental("TIME_SERIES_INTRADAY", {
    symbol: stock,
    market: "USD",
    interval: "5min",
  })
  .then((data) => {
    for (let key in data["Time Series (5min)"]) {
    let openPrice = data["Time Series (5min)"][key]["1. open"];
    prices.push(openPrice);
   }
  console.log(prices[0]);
  return prices[0];
 });
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You must await your promise, or define a then calback :

async function getInput() {//async
  client.on("message", (msg) => {
    if (!msg.content.startsWith(prefix) || msg.author.bot) return;

  const args = msg.content.slice(prefix.length).trim().split(" ");
  const command = args.shift().toLowerCase();

  if (command === "list") {
    msg.channel.send(tickers.join(", "));
  } else if (command == "add") {
    tickers.push(args[0]);
  } else if (command == "price") {
    console.log(await getStockPrices(args[0]));//await
  }
  });
client.login("KEY");
}

Or

function getInput() {
  client.on("message", (msg) => {
    if (!msg.content.startsWith(prefix) || msg.author.bot) return;

  const args = msg.content.slice(prefix.length).trim().split(" ");
  const command = args.shift().toLowerCase();

  if (command === "list") {
    msg.channel.send(tickers.join(", "));
  } else if (command == "add") {
    tickers.push(args[0]);
  } else if (command == "price") {
    getStockPrices(args[0]).then(console.log); //then
  }
  });
client.login("KEY");
}

With promises, the result is asynchronous. And you must, indeed, return your promise in your other function :

function getStockPrices(stock) {
 let prices = [];

 return alpha //there, return your promise
   .experimental("TIME_SERIES_INTRADAY", {
    symbol: stock,
    market: "USD",
    interval: "5min",
  })
  .then((data) => {
    for (let key in data["Time Series (5min)"]) {
    let openPrice = data["Time Series (5min)"][key]["1. open"];
    prices.push(openPrice);
   }
  console.log(prices[0]);
  return prices[0];
 });
}

You should read about Javascript Promises, it'll helpp you understand what you're doing.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda