Use value that is filled after a Promise

Asked

Viewed 39 times

1

Guys, I’m developing an application that, according to the code below, searches the data in an API and with the result of this, makes other calls and makes a push in a variable, how can I access this variable, only after finishing the whole loop of the forEach?

    const leagues = ['22537', '22614', '22821', '24320']
    const data = []

    leagues.forEach(async league => {
      const response = await axios(`${api_link}/v2/events/ended?sport_id=1&league_id=${league}&token=${token}&day=20201105`)
      const totalPages = Math.ceil(response.data.pager.total/response.data.pager.per_page)

      for(let i=1; i<=totalPages; i++){
        const response = await axios(`${api_link}/v2/events/ended?sport_id=1&league_id=${league}&token=${token}&day=20201105&page=${i}`)
        const d = response.data.results

        d.forEach(val => {
          data.push(val)
        })
      }
    })

    console.log(data)

Thank you!!

1 answer

0


I managed to succeed in this way:

const leagues = ['22537', '22614', '22821', '24320']
const data = []
        
const promiseData = leagues.map(async league => {
    const response = await axios(`${api_link}/v2/events/ended?sport_id=1&league_id=${league}&token=${api_token}&day=${actual_date}`)
    const totalPages = Math.ceil(response.data.pager.total/response.data.pager.per_page)
            
    for(let i=1; i<=totalPages; i++){
        const response = await axios(`${api_link}/v2/events/ended?sport_id=1&league_id=${league}&token=${api_token}&day=${actual_date}&page=${i}`)
        const d = response.data.results
                
        d.forEach(val => {
            data.push(val)
        })
    }
})
        
await Promise.all(promiseData)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.