Как отправить несколько запросов на один api

Рейтинг: 0Ответов: 1Опубликовано: 15.01.2023

Есть такой код:

<script>
import axios from "axios";

export default {
  data() {
    return {
      rounds: [],
      matches:[]
    }
  },
  created() {

    axios.get(`https://api.sportsdata.io/v3/csgo/scores/json/CompetitionDetails/${this.$route.params.competitionId}?key=`)
        .then(response => {
          response.data.Seasons.forEach(season => {
            season.Rounds.forEach(round => {
              if (this.$route.params.seasonId == round.SeasonId){
                this.rounds.push(round.RoundId)
              }
            })
          })
        })

    this.rounds.forEach(roundId => {

    axios.get(`https://api.sportsdata.io/v3/csgo/scores/json/Schedule/${roundId}?key=`)
        .then(response => {
          this.matches.push(response.data)
        })
    })
  },
}
</script>

Нужно вставить каждый элемент массива this.rounds в https://api.sportsdata.io/v3/csgo/scores/json/Schedule/{roundid} Почему-то массив this.matches пустой. В массиве rounds есть элементы

Ответы

▲ 1Принят

Axios запросы - это асинхронная операция. Для того, что бы дождаться ответа от первого запроса и выполнить после этого второй запрос, можно организовать цепочку .then()

axios.get(`https://api.sportsdata.io/v3/csgo/scores/json/CompetitionDetails/${this.$route.params.competitionId}?key=`)
        .then(response => {
          response.data.Seasons.forEach(season => {
            season.Rounds.forEach(round => {
              if (this.$route.params.seasonId == round.SeasonId){
                this.rounds.push(round.RoundId)
              }
            })
          })
        })
        .then(res => {
          this.rounds.forEach(roundId => {axios.get(`https://api.sportsdata.io/v3/csgo/scores/json/Schedule/${roundId}?key=`)
              .then(response => {
                this.matches.push(response.data)
              })
          })
        })