2016-10-18 2 views
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 с кодом

+1

Вы не можете вернуться из асинхронного метода. – adeneo

+0

Спасибо @adeneo! Что я мог сделать вместо того, чтобы выполнить ту же задачу? – vcamargo

+0

Вы можете использовать результат только в обратном вызове, или в этом случае обработчик 'then' – adeneo

ответ

1

Вы должны использовать .then для обработки результата обещание:

function getLatitudeOrLongitude(url, LatitudeOrLongitude) { 
    return 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 
    }) 
} 

getLatitudeOrLongitude(url, 'latitude') 
    .then((latitudeOfLondon) => console.log(latitudeOfLondon)); 
Смежные вопросы