2

I am trying to return all the teams in a sports division. The api is as follows:

Call /api/divs/ID, which returns

  • a list of subdivisions (.divInfo)
  • a list of teams in that division (.teams)

For example, I called it with Division 1 (55720), which gave me all the regions as well as a couple teams.

enter image description here From any division, I am trying to assemble the complete list of teams in that division, including subdivisions.

Here is my code:

async getSubteams(id) {
    let vm = this
    return await this.$axios.get(`/api/div/${id}`).then(r => {
        let additionalTeams = r.data.divInfo.map(subDivision => vm.getSubteams(subDivision.DivIDDivision))
        return r.data.teams.concat(...additionalTeams)
    })
}
const teams = await this.getSubteams(this.id)

This does not give me the expected output of a list of team objects. Instead, it is a mix between Promises and teams.

enter image description here

I know this is incorrectly programmed, but how can I maintain the asynchrony of this (i.e. multiple api calls are happening at once) while getting a normal list without promises.

I have debated returning promises and then using Promises.all(...), but that did not seem like the best approach.

Peter S
  • 827
  • 1
  • 8
  • 24
  • I would say Promise.all is the best approach... Your code seems solid with the exception that you are not awaiting the `getSubteams()` calls. Hence why you are seeing the Promise result as opposed to the result. – Chris Jul 10 '20 at 22:04
  • Take a look at https://stackoverflow.com/questions/33438158/best-way-to-call-an-async-function-within-map – Chris Jul 10 '20 at 22:04

1 Answers1

0

Promise.all was the key.

async getSubteams(id) {
    let vm = this
    return await this.$axios.get(`/api/div/${id}`).then(async r => {
        let additionalTeams = await Promise.all(r.data.divInfo.map(subDivision => {
            return vm.getSubteams(subDivision.DivIDDivision)
        }))
        return r.data.teams.concat(...additionalTeams)
    })
}
Peter S
  • 827
  • 1
  • 8
  • 24