-1

I'm making a react-native weather forecast app. And I'm trying to get all the data using 2 promise all methods

This is the function I call in useEffect

async function getData(){
  try{

    Promise.all(_.map(savedPlaces, getCurrentWeather)).then((response) => {console.log("current", response.data)})
    Promise.all(_.map(savedPlaces, getDailyWeather)).then((response) => {console.log("daily", response.data)})

  }
  catch(error){
    console.log(error)
  }
}

The savedPlaces variable is an array with names of the cities I want to get the weather for

And this is one of the two fuctions i use to get the data

const getCurrentWeather = async (places) =>{

  const options = {
    method: 'GET',
    url: 'https://community-open-weather-map.p.rapidapi.com/weather',
    params: {q: places.name, lang: 'null', units: 'metric', mode: JSON},
    headers: {
      'x-rapidapi-host': 'community-open-weather-map.p.rapidapi.com',
      'x-rapidapi-key': 'xxx'
    }
  };

  const request = await axios.request(options).then(response => {console.log(response.data)})

  return request

}

The other funtion is basicaly the same except little changes in options

And the issu is that I can see the data in print out in this code fragment

.then(response => {console.log(response.data)})

inside the getCurrentWeather functions but when I try to print them out in .then after Promise.all I get undefined, same with the other function.

current [undefined, undefined]

And I'm asking how to properly do it

m3k_1
  • 383
  • 4
  • 15
  • 1
    Don't mix classic promises and async/await. Just use one or the other – Liam Mar 28 '22 at 07:59
  • Does this answer your question? [Why is value undefined at .then() chained to Promise?](https://stackoverflow.com/questions/44439596/why-is-value-undefined-at-then-chained-to-promise) – Ivar Mar 28 '22 at 08:04

1 Answers1

2

Here:

const request = await axios.request(options)
    .then(response => {console.log(response.data)})

The callback under then prints the data in the console, but has no return statement (returns undefined). Therefore this

return request

returns undefined wrapped in a promise.

Add return response (or return response.data) after the console.log and it should get better.

mbojko
  • 13,503
  • 1
  • 16
  • 26