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?

6
  • Is this in node.js? Commented Jan 7, 2022 at 18:59
  • Maybe show the exact response for console.log(data); Commented Jan 7, 2022 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: stackoverflow.com/questions/28502639/… Commented Jan 7, 2022 at 19:03
  • Does this answer your question? How to return the response from an asynchronous call Commented Jan 7, 2022 at 19:09
  • you are not using fetch to load a local file, are you? fetch is for executing a ajax request. Commented Jan 7, 2022 at 19:11

2 Answers 2

1

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.)

Sign up to request clarification or add additional context in comments.

Comments

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" ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.