【发布时间】:2017-02-28 09:11:12
【问题描述】:
伙计们!
我正在尝试使用 Google Maps API 获取某个位置的纬度或经度。但我不知道如何使用 Fetch API 及其承诺返回值。
我可以记录纬度和经度:
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
有人能指出我出了什么问题吗?谢谢大家!
编辑:Here你可以找到带有代码的JS Bin
【问题讨论】:
-
你不能从异步方法返回。
-
谢谢@adeneo!我能做些什么来完成同样的任务?
-
您只能在回调中使用结果,或者在本例中为
then处理程序 -
我明白了。所以我应该尝试另一个图书馆吗?也许是 jQuery 的 ajax?
-
不,所有异步代码的工作方式都相同,您必须使用它,并在数据实际返回时访问数据。
标签: javascript ecmascript-6 es6-promise fetch-api