0

Noob question here. Can someone elaborate on why seriesData variable outside the then scope is still an empty object. Additionally, what's the appropriate way of accessing data outside of said scope?

fetchData is a method that returns an array of three objects when successfully resolved.

Obviously, the console.log inside the then scope prints the expected seriesData object with the resulting data from the resolved promise.

Here's the code.

import fetchData from './data';

const seriesData = {};

fetchData()
    .then(res => {
        seriesData.characters = res[0];
        seriesData.locations = res[1];
        seriesData.episodes = res[2];

        console.log(seriesData);
    })
    .catch(error => console.error(error.message));

console.log(seriesData);
Collins Orlando
  • 1,521
  • 4
  • 18
  • 25
  • Asynchronous code is asynchronous. You're accessing the variable just fine outside the `.then()` scope, you're simply logging it to the console before it has a value. – David Nov 04 '19 at 12:32
  • 5
    It's not just you. :-) This confuses a **lot** of people. See the answers to the linked questions, fundamentally the reason `seriesData` is blank when you log it is that the code in the `then` handler hasn't run yet, because it runs *asynchronously*. Use `seriesData` within the `then` callback, or switch to `async`/`await` syntax so you can write your flow-control code even when dealing with asynchronous results. – T.J. Crowder Nov 04 '19 at 12:33

0 Answers0