Request data is not returning correctly

Asked

Viewed 200 times

-1

I’m trying to create a front end based on the Wars star API, my plan was to create an object to then show on the screen. When I make a request(https://swapi.co/films for example), some object properties come as an array of links. So I thought of calling function inside the request to make other requests using AXIOS, but when I return the data, they all come back together. How can I make object properties receive data correctly?

My code goes below:

const urlAPI = 'https://swapi.co/api/'


async function getInformation(arrayURL) {

    arrayData = []
    promisses = []
    arrayURL.forEach(element => {
        console.log(element)
        const promisse = axios(element)
            .then(response => response)
            .then(resp => arrayData.push(resp.name))
        promisses.push(promisse)
    })
    axios.all(promisses)
    console.log(arrayData)
    return await arrayData;

}


axios.get(`${urlAPI}films`)
    .then(response => {
        return (response.data.results)
    })
    .then(resp => {
        // console.log(resp)
        resp.forEach(element => {
            if (element.hasOwnProperty('planets')) {
                element.planets = getInformation(element.planets)
                console.log(element.planets)
            }


        })

    })
    .then(data => {
        console.log(data)
    })
    .catch(error => {
        console.log(error)
    })

Em cada console.log ele deveria mostrar os nomes dos planetas, mas mostra apenas na ultima chamada e ainda fora de ordem

  • What do you mean "they all come back together"? You can give an example?

  • By code, each set of requests I call through the getInformation function should return the values to the element.Planets of each element, however it only returns to the last element and all together in a disorganized way.

  • On each console.log, it should be showing the names of the planets I called the getInformation function, but it shows empty. Only the last one he shows.

1 answer

0


There are many errors regarding the treatment of asynchronism in this code, so much so that it is even difficult to describe the entire flow of the code to explain how it arrived at this final result.

A remarkable mistake is here:

element.planets = getInformation(element.planets)

getInformation is an asynchronous function, it will return you a Promise, not an array of planets, but at no point do you wait for the resolution of this planet.

The implementation of the function getInformation also confused, you populate an array promisse with all your requests, then use axios.all(promisses) to wait for resolution of the Precedents, but does not use await, nor then(), I mean, it doesn’t really wait for resolution, and then finally you do await arrayData. Why? I don’t know what you imagined, but use await in an array has no effect.

Your idea however seems to be correct, if I understand correctly. I will try to adapt the code using fetch for greater accessibility here on the site, the only difference is that you will use axios.get(url) instead of fetch(url).then(r => r.json())

const urlAPI = 'https://swapi.co/api/'

function getInformation(arrayURL) {
  // Com o método map, gero um array de promises que correspondem as requisições
  // Essa função não precisa ser assíncrona, pois não precisamos dos dados das
  // requisições aqui, e portanto não precisamos esperar pela resolução
  const arrayPromise = arrayURL.map(url => fetch(url).then(r => r.json()))
  return Promise.all(arrayPromise)
}

async function fetchData() {
  const response = await fetch(`${urlAPI}films`).then(r => r.json())
  
  // Primeiro loop, faço todas as requisições, mas não espero por suas resoluções
  // dessa forma não preciso esperar pela primeira requisição acabar antes de começar a próxima
  for (const result of response.results) {
    result.planets = getInformation(result.planets)
  }

  // Agora que todas as requisições já foram enviadas, posso esperar pela resolução uma a uma
  for (const result of response.results) {
    result.planets = await result.planets
  }

  console.log(response)
}

fetchData()

This code requires an additional effort to optimize response time. You could just make one request at a time and wait for the answer, it would be simpler, but due to the amount of requests in this code, it would mess up the user experience.

Browser other questions tagged

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