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

时间:2019-04-11 01:08:12

标签: javascript fetch

我正在使用一次获取的结果为HTML中的div生成一些元素。在这些获取的元素内,是我用来获取一些其他元素的URL列表。我的目标是将两次获取的数据合并到HTML div中。我当前的代码正在访问数据,但在最后的div中无法正确合并。

我试图将代码重写为嵌套的访存和函数,并且仍然存在相同的问题。

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()

创建一个元素,其中包含两次提取的数据。

2 个答案:

答案 0 :(得分:0)

您可以使用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
})

答案 1 :(得分:0)

获取返回承诺,您可以链接承诺。 Check this.

尝试此解决方案。

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