0

I've been trying to figure out how to access the data I'm returning from an async function in React while also using Typescript. I'm getting really confused about data types and what I should put where. Hoping someone can help me out. Here is the code of my function making the request, and the function that's using that data:

async getLatLong(location: string): Promise<WeatherAPI> {
        const response = await axios.get<WeatherAPI>(`${this.latLongUrl}q=${location}`)

        return response.data;
    }
    
    async getWeather(location: string) {
        const latLong = this.getLatLong(location);

        console.log(latLong);
    }

And here's the code of the defined interface:

export interface WeatherAPI {
    country: string,
    lat: number,
    local_names: object,
    lon: number,
    name: string,
    state: string
}

I'm not getting an error with this code, but all it's logging is Promise{<pending>} instead of the data I'm expecting. If I try to change console.log(latLong) to console.log(latLong[0]) as the data is an array, I get the error Property '0' does not exist on type 'Promise<WeatherAPI>'.

2
  • 2
    To access the eventual value of a promise, await that promise. So const latLong = await this.getLatLong(location) Commented Jun 19, 2022 at 0:44
  • @NicholasTower Thanks so much. If you want to put that as the answer, I would be happy to accept it. Commented Jun 19, 2022 at 2:03

1 Answer 1

2

One addition to the answer in the comment: you can also use then to handle the promise value:

getLatLong(location).then((latlong) => {...})

Same with await:

const latLong = await this.getLatLong(location)

Read more about promises in the MDN Docs if you're interested.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.