0

我的代码:

var latlng = {lat: 7, lng: 7};

function findLatLng() {
    var testLocation = '350 Victoria St, Toronto';

    axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
        params: {
            address: testLocation,
            key: 'MY KEY',
        }
    })
    .then(function(response) {
        console.log(response.data.results[0].geometry.location);
        return response.data.results[0].geometry.location;
    })
    .catch(function(error) {
        console.log(error);
    });
}

latlng = findLatLng();
console.log(latlng);

在控制台中,latlng被记录为未定义,但console.log(response.data.results[0].geometry.location)被记录为正确的值;
即使它应该首先执行,它也会在之后记录。

我认为这是因为尽管findLatLng()没有完成请求,但代码仍在继续,但我不确定。当我latlng之后在控制台中检查的值时,它变成了正确的值。

请问这是什么问题,我该如何解决?

4

0 回答 0