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

113
Visualizações
javascript fetch extract data

I setup this fetch structure (I learned it here:https://www.kirupa.com/html5/making_http_requests_js.htm), but I can't carry out of the function the data fetched :

var arr = [];
var dat=[1,2];
var prova = 5;
fetch('https://ipinfo.io')
  .then(function(response) {
    return response.text();
  }).then(function(text) {
  arr.push(text);
  dat = arr;
  prova=prova+1;
  //console.log(arr);
  });
console.log(arr);
console.log(dat);
console.log(prova);
//document.getElementById('pText').innerHTML = dat[0];

console.log(arr)  -> undefined
console.log(dat)  -> [1,2]
console.log(prova) -> 5

I defined the variables as global and modified in the function, but the global variables are not changed as expected, do you know why?

thanks in advance for support.

sorry I haven't found the answer to my question in the other linked question: if I put the "console.log" inside my function it works also in my code, the problem is to make visible the results of the fetch outside the function as you see the modifications inside the function don't update the global variables.

For a normal function it works but for an async function not, why? and how to take out the data?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

fetch returns a promise. In the mean time the script will go to the next line outside of the promise, which is in your case console.log(arr);

Your code above is rewriten, using async/await. It makes code a lot more readable in my opinion.

async function run() {
    var response = await fetch('https://ipinfo.io');
    var text = await response.text();

    arr.push(text);
    dat = arr;
    prova = prova + 1;

    console.log(arr);
    console.log(dat);
    console.log(prova);
}

run();
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