如何将Fetch API的值传递给变量
How to pass the value of the Fetch API to a variable?
各位!
我正在尝试使用谷歌地图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
有人能告诉我怎么了吗?谢谢大家!
编辑:在这里你可以找到一个JS Bin,代码为
您必须使用.then
来处理promise的结果:
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));
相关文章:
- 如何将输入范围的值传递给JS中的变量
- jQuery.ajax未将值传递给php变量
- 如何将 Java 脚本值传递给 PHP 变量
- 如何将 C# 变量的值传递给 javascript
- 如何将 html 输入值传递给 php?- 变量不起作用
- 需要将变量 php 的值传递给 javascript,但我不能
- 将JavaScript值传递给PHP变量(有限制)
- 如何使用 AJAX 调用将表单值传递给 PHP 变量
- 将内联 PHP 中的值传递给 JavaScript 变量
- 如何使用同一页面将文本字段值传递给PHP变量
- 将一个值传递给javascript中的一个变量,其中这些值是json中的响应
- 将值传递给php变量
- 在本例中,我如何将ajax变量的值传递给php脚本
- 将变量x的值传递给$res
- 将js变量或输入值传递给razor
- 如何传递更改,将下拉列表的值传递给PHP变量
- 将HTML单选按钮值传递给javascript变量
- 将一个变量值从javascript值传递给php变量
- 如何将angular 2变量's的值传递给javascript函数
- 将选定的值和变量传递给HTML页面