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

时间:2020-01-18 01:01:11

标签: javascript reactjs

我已经尝试解决了一段时间。我有三个功能都可以独立工作。但是,我无法从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>
    );
}

2 个答案:

答案 0 :(得分:3)

调用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--

答案 1 :(得分:3)

我相信您需要在getUserCoordinates上兑现承诺。否则,返回结果将始终是不确定的。

看一下示例笔:https://codepen.io/lessadiogo/pen/ZEYqXRa

干杯