0

I am trying to build a simple crypto portfolio in nodejs by fetching prices from coingecko API. I set up a simple mongodb with all assets and I am parsing through the db and fetching each price. The fetch works as I can console.log the results however I cannot seem to be able to store the prices in a variable that I can call outside the fetch function. Thus, I cannot pass the prices to my ejs file. I am quite new to js (coming from python), and it seems that I am missing someting on how to handle api results, here is my code:

app.get('/dashboard', (req, res) => {
    Holdings.find ((err, allHoldings) => {
        if (err) {
            res.type('html').status(500);
            res.send('Error: ' + err); 
        }
        else if (allHoldings.length == 0) {
            res.type('html').status(200);
            res.send('You have no holdings');
        }
        else {
            var priceList = {};
            allHoldings.forEach(async coin => {
                coin = coin.asset;
                const uri = 'https://api.coingecko.com/api/v3/simple/price?ids=' + coin + '&vs_currencies=usd&include_market_cap=false&include_24hr_vol=false&//include_24hr_change=false&//include_last_updated_at=false';
                const fetch_price = await fetch(uri);
                const json = await fetch_price.json()
                const price = json[coin]['usd'];
                priceList[coin] = price;
                priceList.save;
                console.log(priceList);
                return priceList;
            });
            console.log(priceList);
            res.render('dashboard', { holdings : allHoldings})
        }   
    });
});

As you can see I set a priceList object before performing the API fetch and then I try to push the pair {coin : price} to that object. The first console.log works fine, however the second one only logs an empty object.

Any idea ?

Thanks

NiocTib
  • 80
  • 7
  • Don't use async functions with `.forEach()`... If you want to have these in parallel, use `.map()` instead and put the array of promises in `Promise.all` then `await` that. Or just convert to a normal loop`. – VLAZ Mar 08 '21 at 16:08
  • Hey I have tried to change the code to use .map and promise.all but it is still not working , I have looked at all other similar questions here on stackoverflow but I still don't get it, could you share some demonstration code ? that would be greatly appreciated. – NiocTib Mar 09 '21 at 06:49

0 Answers0