【发布时间】:2020-02-05 09:50:15
【问题描述】:
当我从客户端向服务器发出“GET”请求时,服务器应该向股票 API 发出 axios.get() 调用,以检索一系列代码的数据。当我控制台记录结果时,它似乎工作正常,但数组似乎没有保存,就像它被清除并以空的形式返回客户端一样。我想我可能会用async/await 搞砸这件事。
async function currentPrice(ticker) {
const apiURL = `https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=${ticker}&apikey=${API_KEY}`;
let price;
await axios.get(apiURL).then(data => {
try {
price = data.data["Global Quote"]["05. price"];
} catch (error) {
console.log(error)
}
})
return price;
};
app.get("/refresh", redirectLogin, (req, res) => {
const {
user
} = res.locals;
var array = [];
connection.query(`SELECT * FROM holdings WHERE user_name = '${user.user_name}' AND quantity > 0`, (err, results) => {
if (err) throw err;
results.forEach(holding => {
currentPrice(holding.ticker).then(data => {
var updatedTicker = {
ticker: holding.ticker,
description: holding.description,
price_acquired: holding.price_acquired,
market_price: data,
delta: parseFloat(this.market_price) - parseFloat(this.price_acquired),
quantity: holding.quantity,
trade_date: holding.date_acquired
}
array.push(updatedTicker);
// console.log(array);
console.log(updatedTicker.market_price)
})
})
res.json(array)
})
})
【问题讨论】:
-
在您的任何
currentPrice().then()完成之前,您正在调用res.json()。