Promise

Google Maps JavaScript API 中的非同步方法會傳回 Promise

支援

API 方法是否傳回 Promise
路線
距離矩陣
海拔高度
地理編碼器
最大縮放圖像
地點介面集
Place Autocomplete 服務 部分1
街景服務

用量

請參閱這份指南來瞭解如何使用 Promise,或是查看下方範例來瞭解如何使用 Google Maps JavaScript API 進行非同步方法呼叫。

async 和 await

await 運算子用於等待 Promise,且只能在 async 函式內使用。

const app = async () => {
  const elevationService = google.maps.ElevationService();
  const locations = [{lat: 27.986065, lng:86.922623}];

  const response = await elevationService.getElevationForLocation({locations});
  console.log(response.results);
};

app();

then、catch 和 finally

Promise 物件具有可採用回呼函式的 thencatchfinally 方法。

const elevationService = google.maps.ElevationService();
const locations = [{lat: 27.986065, lng:86.922623}];

const promise = elevationService.getElevationForLocation({locations});

promise
    .then((response) => {
      console.log(response.results);
    })
    .catch((error) => {
      console.log(error);
    });
    .finally(() => {
      console.log('done');
    });

非同步回呼模式

回呼模式仍然有效且受支援。

const elevationService = google.maps.ElevationService();
const locations = [{lat: 27.986065, lng:86.922623}];

const callback = (results, status) => {
  if (status === 'OK') {
    console.log(results);
  } else {
    // handle this case
  }
};

elevationService.getElevationForLocation({locations}, callback);

  1. Promise 目前只能在 getPlacePredictions() 中使用。