简体   繁体   English

AJAX连续调用forEach-为什么我看不到结果?

[英]Successive AJAX calls in a forEach - why can't I see the results?

Note: I know I'm probably doing this the wrong way and I'd like any advice about writing it better. 注意:我知道我可能以错误的方式进行此操作,并且希望获得有关更好地编写它的任何建议。

I have a function that, when given a user id, does calls to two APIs to get 1. A list of all the leagues that userid is in. 2. A list of all users in each of those leagues. 我有一个函数,当给定用户ID时,它会调用两个API以获得1.用户ID所在的所有联赛的列表。2.每个联赛中的所有用户的列表。

$.ajax({
  type: "get",
  url: "/api/user/" + userID,
  dataType: "json",
  success: function(response) {
    response.leagues.classic.forEach(element => {
      if (element.short_name == null) {
        myLeagues.push(element.id);
      }
    });

  }
}).then(function() {
  myLeagues.forEach(leagueid => {
    $.ajax({
      type: "get",
      url: "/api/league/" + leagueid,
      dataType: "json",
      success: function(response) {
        if (response.standings.results.length < 30) {
          response.standings.results.forEach(element => {
            myOpponents.push(element.player_name)
          });
        }
      }
    });
  })
}).then(function() {
  console.log(myOpponents);
  myOpponents.forEach(opponent => {
    console.log(opponent)
  });
})

console.log(myOpponents) outputs an array with all opponents, as expected console.log(myOpponents)按预期输出一个包含所有对手的数组

console.log(opponent) two lines later doesn't output anything. console.log(opponent)两行以后什么都不输出。

Can you explain why that is, and suggest a better way of writing this whole function? 您能解释为什么吗,并提出一种更好的编写整个函数的方法吗? Thanks 谢谢

Try this: 尝试这个:

async function someFunc(userID) {
  let myLeagues = [];
  let myOpponents = [];

  try {
    const results = await $.ajax({
      type: "get",
      url: "/api/user/" + userID,
      dataType: "json"
    });

    results.forEach(element => {
      if (element.short_name == null) {
        myLeagues.push(element.id);
      }
    });

    let leagues = myLeagues.map(leagueid => {
      return $.ajax({
        type: "get",
        url: "/api/league/" + leagueid,
        dataType: "json"
      })
    })

    let leagueDatas = await Promise.all(leagues);

    leagueDatas.forEach(val => {
      if (val.standings.results.length < 30) {
        val.standings.results.forEach(element => {
          myOpponents.push(element.player_name)
        });
      }
    })

    myOpponents.forEach(opponent => {
      console.log(opponent)
    });
  } catch (e) {
    // handle error
  }
}
someFunc(1)

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

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