1
Люди!Как передать значение Fetch API переменной?
Я пытаюсь получить широту или долготу местоположения с помощью API Карт Google. Но я не знаю, как вернуть значение, используя API Fetch и его обещания.
Я могу войти широту и долготу с:
let url = 'https://maps.googleapis.com/maps/api/geocode/json?address=london'
fetch(url)
.then(response => response.json())
.then(data => {
console.log(data.results[0].geometry.location.lat)
console.log(data.results[0].geometry.location.lng)
})
Выход:
51.5073509
0.1277583
Но я хочу, чтобы инкапсулировать этот код в функции:
function getLatitudeOrLongitude(url, LatitudeOrLongitude) {
fetch(url)
.then(response => response.json())
.then(data => {
if (LatitudeOrLongitude === 'latitude')
return data.results[0].geometry.location.lat
else
return data.results[0].geometry.location.lng
})
}
let latitudeOfLondon = getLatitudeOrLongitude(url, 'latitude')
console.log(latitudeOfLondon)
Выход:
undefined
Может кто-нибудь указать мне, что не так? Спасибо вам всем!
Edit: Here вы можете найти JS Bin с кодом
Вы не можете вернуться из асинхронного метода. – adeneo
Спасибо @adeneo! Что я мог сделать вместо того, чтобы выполнить ту же задачу? – vcamargo
Вы можете использовать результат только в обратном вызове, или в этом случае обработчик 'then' – adeneo