无法访问函数内部的地理位置

凯文

我已经尝试了一段时间了。我有三个功能都可以独立工作。但是,我无法从中获取值getUserCoordinates()出现在中fetchCurrentTemp()undefined无论我尝试什么,它都会返回我已经离开JS环境一分钟了,所以也许我错过了一些明显的东西,但是我很沮丧。

fetchCurrentTemp()

import { getUserCoordinates } from './helpers';
const url = 'http://api.openweathermap.org/data/2.5';

export const fetchCurrentTemp = async () => {
    const coordinates = getUserCoordinates();
    console.log('coords:', coordinates);
    // logs 'undefined'
    try {
        let response = await fetch(`${url}/weather?APPID=x&lat=50.7498752&lon=-100.0004158&units=imperial`);
        let output = await response.json();
    } catch (error) {
        console.log(error);
    }
};

getUserCoordinates()

export const getUserCoordinates = () => {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(({ coords }) => {
            console.log(coords);
            //returns a value
            return coords;
        });
    } else {
        alert('Something is wrong');
    }
};

应用程式

import React from 'react';
import { fetchCurrentTemp } from './utils/api_calls';

function App() {
    return (
        <div>
            <button onClick={() => fetchCurrentTemp()}>Hello</button>
        </div>
    );
}
aiyan

调用时return coords您只是从回调函数中退出,而不是退出getUserCoordinates()

您可以使用基于Promise的方法,因为它getCurrentPosition是异步的:

export const getUserCoordinates = () => {
    return new Promise((resolve, reject) => {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(({ coords }) => {
                console.log(coords);
                resolve(coords);
            });
        } else {
            reject('Something is wrong');
        }
    });
};

然后修改fetchCurrentTemp()为包括await

// --snip--
const coordinates = await getUserCoordinates();
// --snip--

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

无法访问函数内部的元素

来自分类Dev

无法使用geoPointForCurrentLocationInBackground检索地理位置

来自分类Dev

地理位置API无法正常工作

来自分类Dev

内部函数更改后无法访问外部函数变量

来自分类Dev

电报地理位置

来自分类Dev

gpsd的地理位置

来自分类Dev

角度地理位置

来自分类Dev

OrientDB地理位置

来自分类Dev

AngularJs地理位置

来自分类Dev

重置地理位置

来自分类Dev

地理位置脚本

来自分类Dev

地理位置配置

来自分类Dev

AppleScript - 地理位置

来自分类Dev

React:无法访问getDefaultProps内部的mixin函数

来自分类Dev

无法访问通过更改函数内部的locals()创建的变量

来自分类Dev

JavaScript内部匿名函数无法访问成员?

来自分类Dev

以编程方式访问地理位置服务

来自分类Dev

在Cordova地理位置中访问模拟蓝牙GPS坐标

来自分类Dev

地理位置函数错误不起作用

来自分类Dev

JavaScript地理位置错误-回调函数错误

来自分类Dev

使用应用程序中嵌入的浏览器时,无法从Android上的网页访问地理位置

来自分类Dev

离子服务:可以通过localhost访问google地理位置api,但是当服务地址更改时,它无法正常工作

来自分类Dev

Phonegap地理位置无法在移动设备上运行

来自分类Dev

无法使用地理位置显示自动缩放地图

来自分类Dev

检查地理位置后功能无法启动

来自分类Dev

无法在Android模拟器中获取地理位置

来自分类Dev

我的googlemap地理位置无法正常工作

来自分类Dev

无法添加Cordova 3.4.0地理位置插件

来自分类Dev

检查地理位置后功能无法启动