我正在尝试使用我在这个 .then() 函数中获得的返回值。我不知道如何解决它



我试图使用我在这个.then()函数中得到的返回值在我的discord bot函数中发送他们输入的任何股票价格的消息。当我在discord函数中运行该函数时,它显示"未定义",但正确的价格正在记录在.then()函数中。请帮助!

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

你必须等待你的承诺,或者定义一个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");
}

使用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,它会帮助你理解你在做什么。

最新更新