Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

184
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda