1

I'm working on a project with the Fetch API. I'd like to use fetch to get some data out of text files and place them into arrays so I can work with them. I'm not sure what code to use to make the variables global. I thought that by initializing the variable outside of the fetch statement, I might be able to use it that way. Here's what I have so far:

animals.txt

cat
dog
rabbit

index.js

const animalArray;
fetch('animals.txt')
    .then((res) => res.text())
    .then(data => {
      animalArray = data.split(/\r?\n/) //how can I access this outside of the fetch statement?
} 
})
Leia_Organa
  • 1,894
  • 7
  • 28
  • 48
  • 3
    In short, you can't. Since fetch is asynchronous, any code that accesses `animalArray` outside the `.then` will probably run before the fetch has finished. Anything that depends on the result of the fetch has to go in the `.then`, directly or indirectly. – CRice May 17 '18 at 17:44
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – CRice May 17 '18 at 17:44
  • Just put the code that works with them inside that `then` callback. – Bergi May 17 '18 at 17:48

2 Answers2

2

Well for one thing, you're trying to reassign a const declaration, which is forbidden. I you wanted your code to work, you'd have to change it to a let. Then, to make it global, bind it to the global object, window in the browser.

However, the principle of asynchronous requests is that you want to wait for the data to arrive before doing something, so placing the fetch's result in the global scope has very limited uses, because you want to be able to know when the data has arrived.

In order to do that, you just have to do whatever there is to do in the .then() of your fetch(). There is almost always a better way to work with asynchronous data than to pollute the global scope and have a complex systems of events or timeouts checking for changes in a particular global variable.

Christophe Marois
  • 6,471
  • 1
  • 30
  • 32
0

The answer to this question depends on how you are manipulating the data. Are you executing code inside a console manually or is your code on a webpage/in a script file?

If you are just executing code in the console then assigning the data to the global object is fine. I would at least print a message to know when the fetch is complete and the data is available to use.

If you are executing the code as a part of a larger script then you need to continue your code in the promise chain or you will run into timing issues. This is because fetch is asynchronous and the data will not be available until it has concluded its request. In general it is better to pass data along as parameters instead of using the global object as it makes the flow of the program more obvious.

Deadron
  • 5,135
  • 1
  • 16
  • 27