Home > Mobile >  React native: async, await, fetch
React native: async, await, fetch

Time:06-23

In my app, I'd like to perform an HTTP request, wait for the request to be completed, and show the result

function HomeScreen({ navigation, route }) {

....

console.log("Try to decode");

const result = GeocodingUtils.getAdressFromCoordinates(myLocation);

console.log("Get Address OK");

<Text>{result}</Text>

And this is my getAdressFromCoordinates method

export default class GeocodingUtils {

static async getAdressFromCoordinates(location) {

    try {
        const response = await fetch("valid_url");
        const responseJson = await response.json();

        .....

        console.log(street   " "   streetNumber);

        return street   " "   streetNumber;

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

I taught that the console output would have been something like:

Try to decode

St. Mary street

Get Address OK

but that's the true output:

Try to decode

Get Address OK

/print a promise object/

So I have two problems:

the first one is that my geocode function should "stop" the code flow execution until its end the second is that I'd like to print the result of my funciont in a Text component

Ty in advance

CodePudding user response:

The problem you 're having is that you 're calling an async method and not waiting for it to respond before storing it in the result const.

That's why you 're getting a Promise back.

try this :

let result;
GeocodingUtils.getAdressFromCoordinates(myLocation).then(r => result = r);

or even better define your function as async:

var HomeScreen = async({ navigation, route }) => {

....

console.log("Try to decode");

const result = await GeocodingUtils.getAdressFromCoordinates(myLocation);

console.log("Get Address OK");

<Text>{result}</Text>

CodePudding user response:

You need to await the GeocodingUtils.getAdressFromCoordinates result:

function HomeScreen({ navigation, route }) {

....

console.log("Try to decode");

const result = await GeocodingUtils.getAdressFromCoordinates(myLocation);

console.log("Get Address OK");

<Text>{result}</Text>

You can also use promises:

function HomeScreen({ navigation, route }) {

....

console.log("Try to decode");

GeocodingUtils.getAdressFromCoordinates(myLocation).then(function(result){
console.log("Get Address OK")
<Text>{result}</Text>
})
  • Related