除非单击两次,否则节点 Axios 不会呈现 api 数据

Node Axios wont render api data unless clicked twice

我正在尝试使用 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() 调用应该被 await 编辑(并且处理函数被设置为 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}); 
});

然而,这只是您当前的问题,这不考虑错误管理 - 但我假设您最终会到达那里。 ;)