Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

242
Vistas
Estoy tratando de usar el valor de retorno que obtengo en esta función .then(). no se como arreglarlo

Estoy tratando de usar el valor de retorno que obtengo en esta función .then() en mi función de bot de discordia para enviar un mensaje de cualquier precio de las acciones que ingresen. Cuando ejecuto la función en la función discord, dice 'indefinido' pero el precio correcto se registra en la función .then(). ¡Por favor ayuda!

 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 Respuestas
Responde la pregunta

0

Debe esperar su promesa, o definir then devolución de llamada:

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

O

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

Con promesas, el resultado es asíncrono. Y debe, de hecho, devolver su promesa en su otra función:

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

Deberías leer sobre Javascript Promises, te ayudará a entender lo que estás haciendo.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda