反应ajax:多个嵌套获取获取 [英] react ajax : multiple nested fetch Get

查看:102
本文介绍了反应ajax:多个嵌套获取获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个功能,它首先获取环境中的所有区域,然后当他为每个区域找到这些区域时,它将对边界点进行api调用. 所有提取均执行,但问题是,如果我尝试写出区域的 length 或尝试执行,则在第一次提取的 then 中. foreach 我得到0.

There is a function that first gets all zones in an environment and then when he found these zones for each zone it will do an api call for the borderpoints. All fetches get executed but the problem is that in the then for the first fetch if I try to write out the length of the zones or try to do a .foreach I get 0.

我知道这是因为它运行异步,并且在我执行console.log时尚未加载,但我应该这样做.这就是为什么我们使用 .then 的原因吗?等待数据加载完毕.

I know this is because it runs async and it is not yet loaded on the moment I do the console.log but I tought it should be. That's why we use the .then isn't it? to wait until the data has been loaded.

要明确:我正在寻找一种使zone.length返回对象数组的实际长度并立即被评估而不是从0开始求值的方法.我找不到方式:

To be clear: I'm looking for a way to make zones.length give back the real length of the array of objects and be evaluated immediately instead of 0. I can't find out how:

这是代码.

getZones(){
      var that = this;
  var zones = new Array();
  fetch('api/environment/zone/1').then(function(response){
    response.json().then(function(data){
      data.forEach(function(element){
        zones[element.zoneID] = element;
        zones[element.zoneID].points = [];
        fetch('api/zone/point/'+element.zoneID).then(function(response){
          response.json().then(function(data){
            data.forEach(function(element){
              zones[element.zoneID].points.push(element);  
            });
          }); //closing of data inner fetch.
          });
        });
      });
    }).then(function(response){
      console.log(zones); //this gives all zones
      console.log(zones.length); //this one gives 0
//the for each is never executed because it's still 0.
      zones.forEach(function(element){  
        console.log(element);
      });
    });
  }

已经非常感谢快速的反应和帮助.

Already a big thanks for the fast Reaction and help.

推荐答案

fetch的调用返回一个Promise,即async.因此,您的第二个.then甚至在第一个.then中的代码完成之前就执行了,因为,您的第一个contains然后是另一个称为异步的fetch函数.您可以使用如下所示的逻辑来等待,直到获得所有点数据,然后继续执行逻辑.

The calls to fetch returns an Promise and that is async. So your second .then executes before even the code inside the first then completes because, your first then contains another fetch function being called which is async. You can have a logic like below to wait until you get all points data and the proceed with your logic.

    getZones(){
          var that = this;
          // var zones = new Array();

          // this function gets called finally.
          // Do what you want to do with zones and points here.
          var gotAllZones = function(zones) {

              console.log(zones); //this gives all zones
              console.log(Object.keys(zones).length); //this one gives 0

              Object.keys(zones).forEach(function(index){  
                console.log(zones[index]);
              });
          }

          fetch('api/environment/zone/1').then(function(response){
            response.json().then(function(data){
              //decleare zones to be a object. Based on your code `zones` is not an array
              var zones = {};
              var pointsDone = 0; // declare how many points api has been completed. Initially its `0`
              data.forEach(function(element){
                zones[element.zoneID] = element;
                zones[element.zoneID].points = [];
                fetch('api/zone/point/'+element.zoneID).then(function(response){
                  response.json().then(function(innerData){
                    innerData.forEach(function(element){
                      zones[element.zoneID].points.push(element);  
                    });
                    pointsDone++; //each time we are done with one. we increment the value.

                    // we check if we are done collecting all points data
                    // if so we can call the final function. 
                    if(pointsDone === data.length) {
                      gotAllZones(zones);
                    }
                  }); //closing of data inner fetch.
                  });
                });
              });
            })
      }

这篇关于反应ajax:多个嵌套获取获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆