为什么在我的循环之后执行JQuery.getJson?

xzv2uavs  于 2022-12-12  发布在  jQuery
关注(0)|答案(1)|浏览(166)

我希望我的数据被排序,因为我可以看到pokeparser函数每次都给出一个url,但getJson是在循环结束后执行的,如何才能同时完成呢?

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?
       .......................
         
        });
  }
cbwuti44

cbwuti441#

这是因为getJSON是异步的,当第一个响应返回时,循环已经结束。

// 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);
  });
}

但是,如果您的目的是在处理完前一个响应后再处理一个响应,则可以使用以下技术:

// 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();
    }
  });
}

相关问题