简体   繁体   中英

Accessing data from an async function in React and Typescript

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>'.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM