0

I am trying to return a few lists with the axios api call i make from the javascript, however, i do not understand how to console.log() the result and pass it for my future use (trying to use it for a data visualization)

heres what i have

const axios = require('axios');

var years = []
var totals = []
var rail = []
var bus = []
var para = []


const getTotal = async () => {
    const url="https://data.cityofchicago.org/resource/w8km-9pzd.json";

    var totals = []
    try {
        let res = await axios.get(url);

        for (i = 0; i < res.data.length; i++) {
            totals.push(res.data[i].total);
            years.push(res.data[i].year);
            rail.push(res.data[i].rail);
            bus.push(res.data[i].bus);
            para.push(res.data[i].para);
        }

    }catch(error) {
        console.log(error);
      }
      return(totals,years,rail,bus,para) 
}

//data = axiosDataFetch().bus;
console.log(getTotal())

^^^ how do i print totals here instead of having it show as undefined? i edited the code based on some answers i received, essentially i want to be able to call and use the 5 lists i got from the API into a data visualization.

MCO
  • 194
  • 2
  • 13

3 Answers3

1

Add an await keyword before the axios call, then instead of using the .then callback, do stuff with the res object.

const axios = require('axios');

async function axiosDataFetch() {
    const url="https://data.cityofchicago.org/resource/w8km-9pzd.json";

    var totals = []
    let res = await axios.get(url);

    for (i = 0; i < res.data.length; i++) {
        totals += res.data[i].total;
    }

    console.log(res.result) 
}

axiosDataFetch();

Javascript is designed with asynchronous behavior at its core (eg. it's unknown when the http call made by axios will return, so it's not guaranteed to be in sync with your program).

You can read more about the many, many ways to handle asynchronous behavior here. Long article, but will save you countless hours in the future if you can understand its content.

McKay M
  • 448
  • 2
  • 8
  • Got an error let res = await axios.get(url); ^^^^^ SyntaxError: await is only valid in async function – MCO May 05 '20 at 01:34
  • Put everything in an asynchronous function, then call it. The answer is updated! Sorry, I forgot to mention that. The link I sent explains more details of this too – McKay M May 05 '20 at 01:38
  • thank you, this is very helpful, how do i get it to return that list of total to use it somewhere else though? – MCO May 05 '20 at 01:45
0

Try logging from inside your then. Your other log is being called before axios returns back a result.

const axios = require('axios');
const url="https://data.cityofchicago.org/resource/w8km-9pzd.json";

var totals = []
let res = axios.get(url)
    .then(result=>function(response){
        for (i = 0; i < response.data.length; i++) {

            totals += response.data[i].total;

          }
         console.log(totals); // add this
    }
    )
    .catch(function (error) {
      console.log(error)
    });   
cham
  • 8,666
  • 9
  • 48
  • 69
0
    const axios = require('axios');
    const url="https://data.cityofchicago.org/resource/w8km-9pzd.json";

    const getTotal = async () => {
      var totals = []
      try {
        let response = await axios.get(url);
        for (i = 0; i < response.data.length; i++) {
            totals.push(response.data[i].total);
        }
        console.log(totals);
      } catch(error) {
        console.log(error);
      }
      return totals;
    }

sorry my fault, I didn't know that you wanted to execute the query at the top level, you have the pending response because the function getTotals is returning a function that is a promise. You can solve it doing the following

getTotal().then(result => {
  console.log(result);
});

Usually we don't have this behaviour because we have our code modularised and when we import our file, our code is internally inside a IIFE.

Gustavo A Olmedo
  • 565
  • 4
  • 13
  • would i console.log getTotals or console.log the totals? either way it didnt give me the list :( – MCO May 05 '20 at 01:37
  • You should use push, not totals += , "totals" is an array that lives inside getTotal, if you want to console "totals" outside the function you need to declare the variable outside. vat totals = []; const getTotal = async () => { // the rest of the function body without the totals declaration } getTotal(); console.log(totals); but yes you can do a console.log(getTotal()); and you shoud get the results. I already update my solution, check it :) – Gustavo A Olmedo May 05 '20 at 01:45
  • it returns Promise { } instead of the list... – MCO May 05 '20 at 01:47
  • what about now? – Gustavo A Olmedo May 05 '20 at 02:00
  • i edited my question a bit too, esentially i want to be able to call the lists and add them into chart.js – MCO May 05 '20 at 02:26