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

Javascript 如何将Fetch API的值传递给变量?,javascript,ecmascript-6,es6-promise,fetch-api,Javascript,Ecmascript 6,Es6 Promise,Fetch Api,伙计们 我正在尝试使用GoogleMapsAPI获取位置的纬度或经度。但我不知道如何使用fetchapi及其承诺返回值 我可以使用以下工具记录纬度和经度: let url = 'https://maps.googleapis.com/maps/api/geocode/json?address=london' fetch(url) .then(response => response.json()) .then(data => { console.log(data.r

伙计们

我正在尝试使用GoogleMapsAPI获取位置的纬度或经度。但我不知道如何使用fetchapi及其承诺返回值

我可以使用以下工具记录纬度和经度:

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
undefined
但我想将此代码封装在函数中:

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)
输出:

51.5073509
0.1277583
undefined
有人能告诉我怎么了吗?谢谢大家


编辑:您可以找到带有代码的JS Bin

您必须使用
。然后
处理承诺的结果:

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));

您无法从异步方法返回。谢谢@adeneo!我可以做些什么来完成相同的任务呢?您只能在回调中使用结果,或者在本例中是
然后
句柄。所以我应该试试另一个图书馆?也许jQuery是ajax?不,所有异步代码都以相同的方式工作,您必须使用它,并在实际返回数据时访问数据。