Why JQuery.getJson executed after my loop?

72 Views Asked by At

I want my data to be sorted as i can see the pokeparser function gives a url every time but getJson is executed after the end of the loop, how can it be done at the same time?

let counter = 151;
for(let i = 1; i <= counter; i++){
    let url = `https://pokeapi.co/api/v2/pokemon/`;
    url = url + i;
    //console.log(url);
    poke_parser(url);    
}
  
function poke_parser(url){
    console.log("before  "+ url); ///////////////////////////////in that time i is taxionomicly
                                  ///////when the loop finished go to get Json 
    jQuery.getJSON(url,function(data){
        console.log("after  "+ url); 
        //////////////////////////instead executed after the loop 
        ////////// What can i do?
        // .......................
    });
}
1

There are 1 best solutions below

2
IT goldman On

This is because getJSON is asynchronous and by the time the first response comes back the loop is already over.

// stub
var jQuery = {
  getJSON: function(url, cb) {
    setTimeout(function() {
      cb({
        something: 12
      })
    }, Math.random() * 1000)
  }
}

let counter = 8;
for (let i = 1; i <= counter; i++) {
  let url = `https://pokeapi.co/api/v2/pokemon/`;
  url = url + i;
  poke_parser(url);
}


function poke_parser(url) {
  console.log("before  " + url);
  jQuery.getJSON(url, function(data) {
    console.log("after  " + url);
  });
}

But if your intention is to process a response only after the previous has been processed then you can use this technique:

// stub
var jQuery = {
  getJSON: function(url, cb) {
    setTimeout(function() {
      cb({
        something: 12
      })
    }, Math.random() * 1000)
  }
}

let counter = 8;
do_one(1)

function do_one(i) {
  let url = `https://pokeapi.co/api/v2/pokemon/`;
  url = url + i;
  poke_parser(url, function() {
    if (i < counter) {
      do_one(i + 1)
    }
  });

}

function poke_parser(url, foo_then) {
  console.log("before  " + url);
  jQuery.getJSON(url, function(data) {
    console.log("after  " + url);

    if (typeof foo_then === "function") {
      foo_then();
    }
  });
}