How to retrieve and store API response data in JavaScript

I’m working on a JavaScript project where I need to fetch information from an external API and use that data later in my code. I’m having trouble getting the actual response data instead of undefined values.

Here’s what I’m currently trying:

const axios = require('axios');

const options = {
  method: 'GET',
  url: 'https://weather-api.example.com/current',
  params: {
    city: 'London',
    date: '2024-01-15'
  },
  headers: {
    'X-API-Key': 'your-api-key-here',
    'Content-Type': 'application/json'
  }
};

axios.request(options)
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error:', error);
  });

The problem is that when I try to access the response data outside of the callback function, I keep getting undefined. I want to run this daily and store the results so I can process them further in my application. What’s the best way to handle this asynchronous data and make it available for the rest of my script?

Your problem is async operations return right away, but the data shows up later. I’ve worked with APIs for years - async/await with proper scoping fixes this. Don’t try accessing data outside the promise chain. Put everything inside the async context:

let weatherData = null;

async function getAndStoreWeather() {
  try {
    const response = await axios.request(options);
    weatherData = response.data;
    
    // Do your processing here while data is available
    processWeatherData(weatherData);
    
  } catch (error) {
    console.error('Failed to fetch weather:', error);
  }
}

getAndStoreWeather();

For daily storage, I just append to a JSON file with timestamps. Works great - I’ve run thousands of API calls this way without losing data.

You’re hitting a classic async issue. JavaScript doesn’t wait for your API call to finish, so when you try to grab the response data outside the .then() block, it’s still undefined. I ran into this exact problem building a data tool last year.

Here’s how I fixed it - wrap everything in an async function:

async function fetchWeatherData() {
  try {
    const response = await axios.request(options);
    return response.data;
  } catch (error) {
    console.error('Error:', error);
    throw error;
  }
}

// Then use it like this
fetchWeatherData().then(data => {
  // Process your data here
  console.log(data);
});

For storing daily data, I’d go with SQLite or just use fs.writeFileSync() for simple file storage. Both have worked great for me in production when I needed reliable data persistence.

you’ve got a scope problem - you’re trying to access data that doesn’t exist yet. been there!

quick fix with a global variable and callback:

let apiData;

function handleData(data) {
  apiData = data;
  // continue with your logic here
}

axios.request(options)
  .then(response => handleData(response.data))
  .catch(error => console.log(error));

for daily storage, just use localStorage or create a simple json file.