0

I'm struggling to see whats wrong here. I'm pulling in some json (yes I know I'm using a text file). I have an array in the global scope I want to push entries to, i'm iterating over the json and pushing it to that array. Only when I log it out It's empty. It's probably something stupid, but any assistance would be greatly appreciated.

let charities = [];
fetch('../mapdata/markers.txt').then(response => {
        if (response.ok) {
            return response.json();
        }
        throw new Error('Network response error.');
    })
    .then(charData => {
        console.log(`inside: ${JSON.stringify(charData, null, 2)}`);
        charData.map(entry => {
            return charities.push(entry);
        });
    })
    .catch(error => {
        console.log('There has been a problem: ', error.message);
    });
console.log(`outside: ${JSON.stringify(charities, null, 2)}`);

And as it type I'm thinking this might be an async issue...

Sharper
  • 327
  • 3
  • 17

1 Answers1

1

You are doing async operation and reading the [] after firing the asyc operation. It will be always empty.

Instead, put then console.log(outside: ${JSON.stringify(charities, null, 2)}); inside second then(), once the data is pushed into the array.

.then(charData => {
    console.log(`inside: ${JSON.stringify(charData, null, 2)}`);
    charData.map(entry => {
        return charities.push(entry);
    });

    console.log(outside: ${JSON.stringify(charities, null, 2)});
})
Ishwar Patil
  • 1,671
  • 3
  • 11
  • 19