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

标签 javascript ecmascript-6 es6-promise fetch-api

各位!

我正在尝试使用 Google Maps API 获取某个位置的纬度或经度。但我不知道如何使用 Fetch API 及其 promise 返回值。

我可以记录纬度和经度:

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

最佳答案

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

关于javascript - 如何将 Fetch API 的值传递给变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40119346/

相关文章:

javascript - Firebase:数据库 + 存储 - 引用帖子正确图像的最佳实践 | Vue.js

JavaScript 不适用于 ICS

javascript - 在 Promise 链中提取函数

javascript - 如何将异步函数映射到列表上?

Javascript 集合 vs 数组 vs 对象定义

javascript - Foreach,等待每次迭代直到收到响应(使js同步)

javascript - 动态检查单选按钮的值(重构题)

javascript - 在 d3 中通过退出转换保持元素顺序 (selection.order)

javascript - 将嵌套对象数组值放入另一个数组

javascript - 向名为 'speak' 的原型(prototype)添加方法