简体   繁体   English

我正在尝试使用我在 this.then() function 中获得的返回值。我不知道如何修复它

[英]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.我正在尝试使用我在 discord 机器人 function 中的 this.then() function 中获得的返回值来发送他们输入的任何股票价格的消息。 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!当我在 discord function 中运行 function 时,它显示“未定义”但正确的价格被记录在.then() function 中。请帮助!

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

You must await your promise, or define a then calback:您必须等待您的 promise,或定义一个then回调:

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 中返回您的 promise:

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.你应该阅读 Javascript Promises,它会帮助你理解你在做什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我不知道如何解决成绩计算器功能 - I don't know how to fix my grade calculator function 我正在尝试使用 shift 键来增加运动,但我不知道该怎么做 - I am trying to create a increase in movement using shift key, but I don't know how to 错误:不是函数。 我该如何解决? - Error : is not a function. How can I fix it? 我正在尝试使用 javasacript 动态创建特定的 html 结构,但不知道该怎么做 - I am trying to create a specific html structure using javasacript dyanamically, but don't know how to do it 我试图从html中的json获取数据。 我不想使用Ajax,因为 - I am trying to get the data from json in html. I don't want to use Ajax because 所以我试图在一个数组中获取我的 axios 响应,但我不知道该怎么做 - So i'm trying to get my axios response in an array and I don't know how to do it 我正在尝试调用 switch_func function。 但不知何故无法得到想要的结果 - I am trying to call the switch_func function. But somehow not able to get the desired result 我不知道如何解决我的反向数组/字符串 - I don't know how to fix my reverse array/string 我不知道如何解决事件问题? - I don't know how to fix problem with events? 我不知道如何修复 javascript func 中的这个错误 - I don't know how to fix up this bug in javascript func
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM