如何将Fetch API的值传递给变量

How to pass the value of the Fetch API to a variable?

本文关键字:值传 变量 API Fetch      更新时间:2023-09-26

各位!

我正在尝试使用谷歌地图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));