0

I am trying to fetch a javascript file and return the response object as an array. My javascript file is simply an array like ["1", "2", "3", ...] Here is my code right now:

function getNames() {
 let data = fetch('/path/to/file')
 .then((response) => response.json())
 .then(data => {
   console.log(data);
 return data()
 })
 .catch(error => {
   return error;
 });
}

I need to find a way to use the data variable outside of the function. How can I do this?

  • Is this in node.js? – MrMythical Jan 07 '22 at 18:59
  • Maybe show the exact response for `console.log(data);` – Kinglish Jan 07 '22 at 19:00
  • There are a few questions like this on SO. This one recommends eval() - but you should really google the security implications of using that approach: https://stackoverflow.com/questions/28502639/convert-string-loaded-from-text-file-to-an-array-object-in-javascript – Kinglish Jan 07 '22 at 19:03
  • Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – derpirscher Jan 07 '22 at 19:09
  • you are not using `fetch` to load a local file, are you? `fetch` is for executing a ajax request. – derpirscher Jan 07 '22 at 19:11
  • @MrMythical yes –  Jan 07 '22 at 19:48

2 Answers2

0

let data = [];
(
  function() {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(response => response.json())
      .then(json => {
        data = [...json]
      })
  }

)();

// this is outside - might be empty, if the response does
// not arrive under 3 seconds
setTimeout(() => {
  console.log("data in setTimeout", data)
}, 3000)

If you want to update the state of your app reactively (based on whether the area has arrived or not), then you should use a reactive library/framework like React, Vue, Angular or Svelte. (Of course, you can create your own reactivity system, but that might be limiting later.)

muka.gergely
  • 8,063
  • 2
  • 17
  • 34
0

You are using node.js, so you can use require() if you use module.exports

./someFile.js

module.exports = {
  foo: "bar"
}

./otherFile.js

const data = require("./someFile.js")
console.log(data.foo) // "bar"

If you are asking to get a simple array or object from a file, you should be using .json files, and use require() just like in the first example. If you want to get the current data, rather than the data you get when you first require it, use the fs module

./array.json

[
  "1",
  "2",
  "3"
]

./otherFile.js

const fs = require("fs")
const data = JSON.parse(
  fs.readFileSync("./array.json", "utf8")
)
console.log(data) // [ "1", "2", "3" ]
MrMythical
  • 8,908
  • 2
  • 17
  • 45