简体   繁体   English

如何使此功能与Asyn / await同步

[英]How can I make this function synchronous with Asyn/await

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. 我试图使这段代码是同步的,但是由于某种原因async / await无法正常工作。我在React-native中使用两个不同的模块工作。 I want to see my geolocation in googleMaps but it gets me a error because the asynchronous stuff. 我想在googleMaps中查看我的地理位置,但是因为异步的东西,它给我一个错误。

App is the root component, im importing getLocalitation function. 应用程序是根组件,它导入了getLocalitation函数。

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

await / async do not stop code being asynchronous. await / async不要停止异步代码。

They are tools which let you write non-asynchronous style code by managing promises. 它们是使您可以通过管理Promise编写非异步样式代码的工具。

You can only await a promise. 您只能await诺言。 getLocalitation does not return a promise. getLocalitation不返回承诺。

See How do I convert an existing callback API to promises? 请参阅如何将现有的回调API转换为Promise? to get a promise for navigator.geolocation.getCurrentPosition . 获得对navigator.geolocation.getCurrentPosition的承诺。

It is because you're using await keyword with a function that is not async 这是因为您将await关键字与非异步功能一起使用

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. 您可以在定义getLocation时将异步放在()之前,也可以只从const resp = await getLocalitation()删除await ,因为您不需要将await与不返回promise的东西一起使用。

In case you want to make getLocalitation async you do it like this 如果您想使getLocalitation异步,您可以这样做

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;
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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