简体   繁体   English

如何在嵌套获取功能之间传递数据

[英]How to pass data between nested fetch function

I am using the results from one fetch to generate some elements for a div in my HTML. 我正在使用一次获取的结果为HTML中的div生成一些元素。 Within these fetched elements is a list of URLS I am using to fetch some additional elements. 在这些获取的元素内,是我用来获取一些其他元素的URL列表。 My goal is to merge data from both fetches into an HTML div. 我的目标是将两次获取的数据合并到HTML div中。 My current code is accessing the data, but not merging correctly in the final div. 我当前的代码正在访问数据,但在最后的div中没有​​正确合并。

I've attempted to rewrite the code into nested fetches and functions and the same issue persists. 我试图将代码重写为嵌套的访存和函数,并且相同的问题仍然存在。

var request = new XMLHttpRequest()

request.open('GET', 'https://statsapi.web.nhl.com/api/v1/teams/14?expand=team.roster', true)

var age =""
var height = ""
var weight = ""
var nationality = ""


request.onload = function () {
  var data = JSON.parse(this.response)
  var team=data.teams[0].roster.roster

  for (index = 0; index < team.length; ++index){
    var name = JSON.stringify(team[index].person.fullName).replace(/"/g,'');
    var position = JSON.stringify(team[index].position.name).replace(/"/g,'');
    var num = JSON.stringify(team[index].jerseyNumber).replace(/"/g,'');
    var div = document.createElement("div");
    var link = JSON.stringify(team[index].person.link).replace(/"/g,'');


    fetch('https://statsapi.web.nhl.com' + link)
        .then(function(response) {
            return response.json();
        })
        .then(function(myJson) {
            age = JSON.stringify(myJson.people[0].currentAge);
            height = JSON.stringify(myJson.people[0].height);
        weight = JSON.stringify(myJson.people[0].weight);
            nationality = JSON.stringify(myJson.people[0].nationality);
        });

      div.innerHTML='<a href="#" class="list-group-item" data-toggle="collapse" data-target="#sm" data-parent="#menu">' + name + ' <span class="label label-info">' + num + '</span></a>'
        div.innerHTML=div.innerHTML + '<div id="sm" class="sublinks collapse">'
      div.innerHTML=div.innerHTML + '<a class="list-group-item small"><span class="glyphicon glyphicon-chevron-right"></span>' + age + ' </a>'
      div.innerHTML=div.innerHTML + '<a class="list-group-item small"><span class="glyphicon glyphicon-chevron-right"></span>' + height + ' </a>'
      div.innerHTML=div.innerHTML + '<a class="list-group-item small"><span class="glyphicon glyphicon-chevron-right"></span>' + weight + ' </a>'
      div.innerHTML=div.innerHTML + '<a class="list-group-item small"><span class="glyphicon glyphicon-chevron-right"></span>' + nationality + ' </a>'
      div.innerHTML=div.innerHTML + '<a class="list-group-item small"><span class="glyphicon glyphicon-chevron-right"></span>' + position + ' </a> </div>'
    document.getElementById("main").appendChild(div);
  }
}


// Send request
request.send()

Create an element that contains data from both fetches. 创建一个包含两次获取数据的元素。

You can use Promise.all to achieve your functionality 您可以使用Promise.all来实现您的功能

fetch('url1').then(response1 => response1.json()).then(result =>{
// write you data extraction logic here

// do fetch call from fetched data

var fetch2 = fetch('url2').then(response2 => response2.json())
return Promise.all(Promise.resolve(result), fetch2)
}).then(allResult => {

// here you will have data from both the fetch call
})

Fetch returns promises and you can chain promises. 取回承诺,您可以链接承诺。 Check this. 检查一下。

Try this solution. 试试这个解决方案。

fetch('https://statsapi.web.nhl.com/api/v1/teams/14?expand=team.roster')
.then(response => {
    return response.json().then(data => data.teams[0].roster.roster);
}).then(teams => {
      for(team of teams) {
         const {jerseyNumber, person:{fullName, link}, position:{name}} = team;

         fetch('https://statsapi.web.nhl.com' + link)
            .then(res => {
                return res.json().then(data => data.people[0]);
            }).then(people => {
               const {currentAge, height, weight, nationality} = people;

               // Rest of the code. Create div elements.. 
               console.log(`Age: ${currentAge}, Height: ${height}, Weight: ${weight}, Nationality: ${nationality}, Num: ${jerseyNumber}, Name: ${fullName}, Position: ${name}`);
            });
      }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM