Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

175
Vistas
How can I fetch a javascript file and store the response object as an array?

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?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

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" ]
about 4 years ago · Juan Pablo Isaza Denunciar

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda