Node Axios不会渲染api数据,除非单击两次



我正在尝试使用axios获取api数据(这正在工作(,并在按下锚点标记的同时进行渲染。

不幸的是,我不得不点击两次,一次是获得api数据(我可以在控制台中看到它(,然后我不得不再次按下以渲染数据。我不知道该怎么修。

const getCrypto =  async () => {
try {
const response = await axios.get(url)
if(response){
crypto =  response.data;
console.log(crypto)
};
} catch (err){
console.log(err)
}
}
app.get('/', function (req,res){
money = GBP;
getCrypto();
res.render('index.ejs', {cryptos:crypto, money:money}); 
})

基本上:getCrypto()调用应该是awaited(并且处理程序函数被设置为async以允许使用await关键字(。

它之所以能在2次点击中工作,是因为变量crypto似乎是一个全局变量——这是一种危险的做法。

这里有一种更可读的编码方式:

const getCrypto = async () => {
try {
const response = await axios.get(url);
if (response) {
// this goes into a local (const-declared) variable...
const crypto = response.data;
console.log(crypto);
// ...and return it
return crypto;
};
} catch (err) {
console.log(err);
}
};
app.get('/', async (req, res) => {
money = GBP;
// await the result and put it in a local (const-declared) variable...
const crypto = await getCrypto();
// ...and push it to your renderer
res.render('index.ejs', {cryptos: crypto, money: money}); 
});

然而,这只是您当前的问题,这还不包括错误管理,但我认为您最终会达到目的。(

最新更新