【问题标题】:How to pass the value of the Fetch API to a variable? [duplicate]如何将 Fetch API 的值传递给变量? [复制]
【发布时间】: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


【解决方案1】:

您必须使用.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));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-30
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多