0

I trying to add object into array. But when i console log got empty array. Please check i am doing anything wrong. (When i console log instead of push it working fine)

const fs = require("fs");
const XLSX = require("xlsx");
const axios = require('axios');

// Read the file into memory
const workbook = XLSX.readFile("excel.xlsx");

let worksheet = workbook.Sheets[workbook.SheetNames[0]];
// 3683
const jsonArr = [];

function addData() {
  for(let i = 2; i < 4; i++) {
    var add = worksheet[`C${i}`].v;
    axios.get('https://api.opencagedata.com/geocode/v1/json', {
      params : {
        q:add,
        key:keys
      }
    }
    )
    .then(function(res) {
      // console.log(res.data.results[2].geometry);
      jsonArr.push(res.data.results[2].geometry);
    })
    .catch(function(err) {
      console.log(err);
    })
  }
}
addData();
console.log(jsonArr);

1 Answers1

-1

This is a common problem if using promises. Instead, try creating the structure in this() and then return it, so you can then retrieve it from the chain e.g.:

const result = axios.get(...).then(res => res.data.results[2].geometry);

and then for example add it to the outer array.

Or instead use async/await to ensure the request has properly finished:

const result = await axios.get(...);
Peter Badida
  • 11,310
  • 10
  • 44
  • 90