[英]I am trying to use the return value that I get in this .then() function. I don't know how to fix it
我正在尝试使用我在 discord 机器人 function 中的 this.then() function 中获得的返回值来发送他们输入的任何股票价格的消息。 当我在 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];
});
}
您必须等待您的 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");
}
或者
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");
}
有了承诺,结果是异步的。 实际上,您必须在另一个 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];
});
}
你应该阅读 Javascript Promises,它会帮助你理解你在做什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.