-1

I'm trying to make this code to be synchronous but for some reason async/await doesn't work.. Im working in React-native with two differents modules. I want to see my geolocation in googleMaps but it gets me a error because the asynchronous stuff.

App is the root component, im importing getLocalitation function.

export default class App extends Component {
    Appmetod = async () => {
        const resp = await getLocalitation();
        console.log('Appmetod: latitud: ' + resp.latitude);
        Linking.openURL(`http://www.google.com/maps/place/-33.317597,-71.405500`);
    }
    render() {
        return (
            <View style={styles.container}>
              <Button title="Click me" onPress={this.Appmetod } />
            </View>
        );
    }
}

const getLocalitation = () =>{
    console.log('DENTRO DE GetLocalitaion');

    const geoOptions={
        enableHighAccuracy: true,
        timeOut: 10000
    };

    const coordenates =  navigator.geolocation.getCurrentPosition( geoSucces,goFailure, geoOptions);
    console.log('DESPUES DE COORDENATES');

    return coordenates;
} 

const geoSucces = (position) => {
    console.log('DENTRO DE GEOSUCCEES');

    const latitude = position.coords.latitude;
    const longitude = position.coords.longitude;

    const coordenates={
        latitude: latitude,
        longitude: longitude
    };

    console.log('COORDENATES: ' + coordenates.latitude);
    return coordenates;
}

const goFailure = (err) => {
    console.log('Error en al geolocalizar: ' + err);
    return null;
}

OUTPUT:

C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\Utilities\infoLog.js:16 Running application "geolocation" with appParams: {"rootTag":161}. __DEV__ === true, development-level warning are ON, performance optimizations are OFF
C:\Users\jnunez\React-Native\Proyects\geolocation\src\getLocalitation.js:2 DENTRO DE GetLocalitaion
C:\Users\jnunez\React-Native\Proyects\geolocation\src\getLocalitation.js:10 DESPUES DE COORDENATES
C:\Users\jnunez\React-Native\Proyects\geolocation\src\getLocalitation.js:16 DENTRO DE GEOSUCCEES
C:\Users\jnunez\React-Native\Proyects\geolocation\src\getLocalitation.js:26 COORDENATES: -32.92098393
C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\YellowBox\YellowBox.js:67 Possible Unhandled Promise Rejection (id: 0):
TypeError: Cannot read property 'latitude' of undefined
TypeError: Cannot read property 'latitude' of undefined
    at _callee$ (blob:http://localhost:8081/19d9ce97-42d2-4939-91b8-160b264c9c79:1895:58)
    at tryCatch (blob:http://localhost:8081/19d9ce97-42d2-4939-91b8-160b264c9c79:41538:19)
    at Generator.invoke [as _invoke] (blob:http://localhost:8081/19d9ce97-42d2-4939-91b8-160b264c9c79:41713:24)
    at Generator.prototype.<computed> [as next] (blob:http://localhost:8081/19d9ce97-42d2-4939-91b8-160b264c9c79:41581:23)
    at tryCatch (blob:http://localhost:8081/19d9ce97-42d2-4939-91b8-160b264c9c79:41538:19)
    at invoke (blob:http://localhost:8081/19d9ce97-42d2-4939-91b8-160b264c9c79:41614:22)
    at blob:http://localhost:8081/19d9ce97-42d2-4939-91b8-160b264c9c79:41624:15
    at tryCallOne (blob:http://localhost:8081/19d9ce97-42d2-4939-91b8-160b264c9c79:45254:14)
    at blob:http://localhost:8081/19d9ce97-42d2-4939-91b8-160b264c9c79:45355:17
    at blob:http://localhost:8081/19d9ce97-42d2-4939-91b8-160b264c9c79:46233:21
console.warn @ C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\YellowBox\YellowBox.js:67
onUnhandled @ C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\Promise.js:45
onUnhandled @ C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\promise\setimmediate\rejection-tracking.js:71
(anonymous) @ C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\Core\Timers\JSTimers.js:256
_callTimer @ C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\Core\Timers\JSTimers.js:152
callTimers @ C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\Core\Timers\JSTimers.js:414
__callFunction @ C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:366
(anonymous) @ C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:106
__guard @ C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:314
callFunctionReturnFlushedQueue @ C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:105
(anonymous) @ debuggerWorker.js:80
Braven
  • 484
  • 1
  • 6
  • 27
  • Solved: `return new Promise ((resolve, rejection) => { navigator.geolocation.getCurrentPosition( (position) =>resolve(position.coords),rejection, geoOptions); });` is the way – Braven Jun 17 '19 at 20:17

2 Answers2

2

await / async do not stop code being asynchronous.

They are tools which let you write non-asynchronous style code by managing promises.

You can only await a promise. getLocalitation does not return a promise.

See How do I convert an existing callback API to promises? to get a promise for navigator.geolocation.getCurrentPosition.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • How would you do it in this case? Restructuring the code and executing http://www.google.com/maps/place/${resp.latitude},${resp.longitude} inside geoSucces ?? are there any other options? – Braven Jun 17 '19 at 18:54
  • @Braven — I'd wrap `navigator.geolocation.getCurrentPosition` in a promise and return that promise. – Quentin Jun 17 '19 at 18:59
  • I tried this but it didn't work [link](https://gist.github.com/BravenxX/d7d79c09537847109e1a76565504f9a1) I dont understand – Braven Jun 17 '19 at 19:47
0

It is because you're using await keyword with a function that is not async

const resp = await getLocalitation();

You can either put an async before the () when defining getLocation or you can just remove await from const resp = await getLocalitation(), since you don't need to use await with something that does not return a promise.

In case you want to make getLocalitation async you do it like this

const getLocalitation = async () =>{
    console.log('DENTRO DE GetLocalitaion');

    const geoOptions={
        enableHighAccuracy: true,
        timeOut: 10000
    };

    const coordenates =  navigator.geolocation.getCurrentPosition( geoSucces,goFailure, geoOptions);
    console.log('DESPUES DE COORDENATES');

    return coordenates;
} 
  • That won't work. `navigator.geolocation.getCurrentPosition` **is** async (but it doesn't return a promise). – Quentin Jun 17 '19 at 18:32
  • you're right, it only fixes the async/await error. I'd go on a different approach by passing a method reference. – Gabriel Azevedo Jun 17 '19 at 18:34
  • If I want the AppMetod to make this: Linking.openURL(`http://www.google.com/maps/place/${resp.latitude},${resp.longitude}`) will doesn't work: resp.latitude=undefined... How can i fix this? – Braven Jun 17 '19 at 18:39
  • You'll need to do something this like this https://jsfiddle.net/mszfkjpo/ – Gabriel Azevedo Jun 17 '19 at 18:53
  • thx it worked! But how can I do it without linking.operURL inside the callback of navigator? I mean, like a sync code like my example,, – Braven Jun 17 '19 at 19:09
  • Not with `navigator.geolocation.getCurrentPosition`, since it works with callbacks – Gabriel Azevedo Jun 17 '19 at 20:12