Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

112
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!