【问题标题】:How to fetching an API and using the value obtained in another function?如何获取 API 并使用在另一个函数中获得的值?
【发布时间】:2019-04-01 06:07:54
【问题描述】:

我正在使用来自 ES6 的新 fetch 接口来获取 ISS(国际空间站)的地理位置并在谷歌地图中呈现,但我不知道如何将值传递给其他函数iss_position

export async function currentPosition() {
  const fetchResult = fetch('http://api.open-notify.org/iss-now.json');
  const response = await fetchResult;
  const iss_position = await response.json();
}

export function initMap() {
  let map = new google.maps.Map(document.getElementById('map'), {
    center: iss_position,
    zoom: 5,
  });
  let marker = new google.maps.Marker({
    position: iss_position,
    map: map,
  });
}

currentPosition();
initMap();

【问题讨论】:

  • 你的currentPosition 函数没有返回任何东西。
  • 我知道!我需要从第一个函数修改或更改以全局公开 iss_position 的值并从第二个函数访问?
  • 用 currentPossition 返回的值调用 initmap 并确保从 currentPossition 返回 iss 位置。

标签: javascript google-maps async-await es6-promise fetch-api


【解决方案1】:
async function currentPosition() {
  const fetchResult = fetch('http://api.open-notify.org/iss-now.json');
  const response = await fetchResult;
  const iss_position = await response.json();
  // Calling initMap with iss_position
  initMap(iss_position);
}

function initMap(iss_position) {
  let map = new google.maps.Map(document.getElementById('map'), {
    center: iss_position,
    zoom: 5,
  });
  let marker = new google.maps.Marker({
    position: iss_position,
    map: map,
  });
}

currentPosition();

// Please check if this write way to export multiple things or not.
// I'm a NodeJS developer and this is how we do in node.
export = {
    currentPosition,
    initMap
}

【讨论】:

    【解决方案2】:

    这应该可行:

    async function currentPosition() {
      const fetchResult = fetch('http://api.open-notify.org/iss-now.json');
      const response = await fetchResult;
      const data = await response.json();
      const { latitude, longitude } = data.iss_position;
      initMap(latitude, longitude);
    }
    
    function initMap(latitude, longitude) {
      let map = new google.maps.Map(document.getElementById('map'), {
        center: { lat: latitude, lng: longitude },
        zoom: 5,
      });
      let marker = new google.maps.Marker({
        position: { lat: latitude, lng: longitude },
        map: map,
      });
    }
    
    currentPosition();
    
    export { currentPosition, initMap };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-13
      • 1970-01-01
      • 2012-10-28
      • 1970-01-01
      • 2020-01-28
      • 2022-07-07
      相关资源
      最近更新 更多