0

When using unirest to make a call to the CoinGecko API to fetch data, the code is executed before the API data is retrieved.

Every time in the loop (different api call )I want to recieve to data first and then format the data

When the loop is finished I want to console.log the APISparkline object.

I have looked into async function and await. But it doesnt seem to be working (I tought because of unirest?).

How should I go about doing this?

This is the code:

//Initialize unirest
var unirest = require("unirest");

//Combined array
var JSONApiData = ['bitcoin', 'ethereum', 'ripple'];
var ApiSparkline = [];

//Request function
function request() {

    //Send api request for every item in JSONApiData
    for (let i = 0; i < JSONApiData.length ; i++) {
        var reqPriceChart = unirest("GET", "https://api.coingecko.com/api/v3/coins/" + JSONApiData[i] + "/market_chart?vs_currency=usd&days=7");

        //Check if request is succesfull
        reqPriceChart.end(function (res) {
            if (res.error) {
                console.log("An error has occured..");
            } else {
                console.log("Succesfull call to api for sparkline");
            }



           // Format data

            var reqPriceChartData = res.body;
            //Show what api call
            console.log("ID: "+ JSONApiData[i]);

            //push id to object
            ApiSparkline.push({
                "id": JSONApiData[i]
            });

            //push x and y axes to object
            for (let j = 0; j < 5 ; j++) {
                ApiSparkline.push({
                    "x": reqPriceChartData['prices'][j][0]
                });
                console.log("x", reqPriceChartData['prices'][j][0]);

                ApiSparkline.push({
                    "y": reqPriceChartData['prices'][j][1]
                });
                console.log("y", reqPriceChartData['prices'][j][1]);
            }
        });

    }
    //show object
    console.log("waiting for the sparkline data...");
    console.log(ApiSparkline);
}

//Call request function
request();

output:

waiting for the sparkline data...
[]
Succesfull call to api for sparkline
ID: bitcoin
x 1571652143102
y 8210.828818981763
x 1571655778284
y 8264.755772567336
x 1571659368289
y 8233.432839849916
x 1571662936323
y 8242.756913134728
x 1571666644233
y 8237.912825773623
Succesfull call to api for sparkline
ID: ethereum
x 1571652178307
y 174.0092721388111
x 1571655776988
y 177.0068254766295
x 1571659356667
y 176.37099245444682
x 1571662976930
y 176.42993503814898
x 1571666570863
y 176.53393381577698
Succesfull call to api for sparkline
ID: ripple
x 1571652152187
y 0.29061900104026633
x 1571655779102
y 0.2921855341791707
x 1571659359600
y 0.29111232732568143
x 1571662953340
y 0.2922700890418685
x 1571666564610
y 0.29294026245415533
AttackTheWar
  • 219
  • 1
  • 12
  • 1
    `async`/`await` would indeed help here. To do that, you need to [wrap unirest in a promise API](https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises), something like this: `function unirestp(...args) { return new Promise((resolve, reject) => { unirest(...args).end(res => { if (res.error) { reject(res.error); } else { resolve(res.body); } }); }); }` Then make your `request` an `async` function, and `await` the call to `unirestp`. – T.J. Crowder Oct 28 '19 at 09:47
  • 1
    Something along these lines (but note the `***` comments): https://pastebin.com/Zr8phVQK – T.J. Crowder Oct 28 '19 at 09:56
  • @T.J.Crowder Thanks alot for the response it was really helpfull! Since the api calls are asynchronous the output if the ID is always random (ripple, ethereu, bitcoin: ethereum,ripple,bitcoin etc.) How can I have I in the same arrange as in the ApiSparkLine List? ('bitcoin', 'ethereum', 'ripple') – AttackTheWar Oct 28 '19 at 14:45
  • Ah, in that case you want to push to `ApiSparkLine` after the requests have finished, [like this](https://pastebin.com/kzZuwfNs). – T.J. Crowder Oct 28 '19 at 14:57

0 Answers0