Home > Mobile >  javascript for loop with API request
javascript for loop with API request

Time:02-06

I'm used to PHP, doing first thing in js/nodejs. I guess this is some sync/async problem. I have array of currencies and trying to do a for loop with API call. In output you can see three different json outputs (different order everytime) but when I am trying to save the value in the file, I get only the last one from array. Also the var c has same value in console logs (TESTBTC) array:

TESTUSDT,TESTUSD,TESTBTC,

code:

const axios = require('axios');
const fs = require('fs');

var currencies = (fs.readFileSync('funding_currencies.txt', 'utf-8'));
const currencies_array = currencies.split(",");

for (i = 0; i < currencies_array.length - 1; i  ) {
  var c = currencies_array[i];

  if (fs.existsSync('frr_'   c   '.txt')) {
    var oldfrr = (fs.readFileSync('frr_'   c   '.txt', 'utf-8'));
    fs.writeFile("frr_"   c   "_old.txt", oldfrr, function (err) {
      if (err) {
        return console.log(err);
      }
    });
  }

  console.log("funding/stats/"   c   "/hist");

  var baseUrl = "https://api-pub.bitfinex.com/v2/";
  var pathParams = "funding/stats/f"   c   "/hist";
  var queryParams = "limit=1";

  axios.get(`${baseUrl}/${pathParams}?${queryParams}`)
  .then(response => {
    console.log(response.data);
    var raw = JSON.stringify(response.data);
    var partsArray = raw.split(',');
    var frr = 100 * 365 * partsArray[3];
    console.log(c   ' - Daily Rate % FRR: '   frr);

    fs.writeFile("frr_"   c   ".txt", frr, function (err) {
      if (err) {
        return console.log(err);
      }
      console.log("FRR for "   c   " saved to file");
    });
  }, error => {
    console.log(error);
  })

}

output:

funding/stats/TESTUSDT/hist
funding/stats/TESTUSD/hist
funding/stats/TESTBTC/hist
[
  [
    1675598700000,   null,
    null,            0.00000128,
    39.56,           null,
    null,            748236.20624443,
    676828.07200483, null,
    null,            10865216.1584813
  ]
]
TESTBTC - Daily Rate % FRR: 0.04672
[
  [
    1675598700000,   null,
    null,            0.00002035,
    69.88,           null,
    null,            519081.88192342,
    519081.08203316, null,
    null,            0
  ]
]
TESTBTC - Daily Rate % FRR: 0.742775
[
  [
    1675598700000,    null,
    null,             0.00000386,
    28.31,            null,
    null,             6372417.33205204,
    6372417.33205204, null,
    null,             0
  ]
]
TESTBTC - Daily Rate % FRR: 0.14089000000000002
FRR for TESTBTC saved to file
FRR for TESTBTC saved to file
FRR for TESTBTC saved to file

So I need to save the values in right associations in right files

CodePudding user response:

You have only one variable c, which is accessed by all the asynchronous response => {...} functions spawned by the axios.get statements. Because of their asynchronousness, all these functions will see the last value that c takes.

To get one variable per execution, replace the for loop with the following:

currencies_array.forEach(function(c) {
  if (fs.existsSync('frr_'   c   '.txt')) {
  ...
}
  • Related