This question already has answers here:
How do I return the response from an asynchronous call?

(42个答案)


在11个月前关闭。




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

最佳答案

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

09-17 09:24