小编Roe*_*oel的帖子

react ajax:多个嵌套获取获取

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

我知道这是因为它运行异步并且在我执行 console.log 的那一刻还没有加载,但我认为它应该是。这就是我们使用.then的原因不是吗?等待数据加载完毕。

需要明确的是:我正在寻找一种方法让 zone.length 返回对象数组的实际长度并立即进行评估而不是 0。我不知道如何:

这是代码。

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);
      });
    }); …
Run Code Online (Sandbox Code Playgroud)

ajax asynchronous get fetch reactjs

5
推荐指数
1
解决办法
2852
查看次数

标签 统计

ajax ×1

asynchronous ×1

fetch ×1

get ×1

reactjs ×1