Google Maps JavaScript API 中的异步方法会返回 promise。
支持
| API | 方法是否返回 promise | 
|---|---|
| 路线 | 是 | 
| 距离矩阵 | 是 | 
| 海拔 | 是 | 
| 地理编码器 | 是 | 
| 图像最大缩放级别 | 是 | 
| 地点 | 否 | 
| 地点自动补全服务 | 部分支持1 | 
| 街景 | 是 | 
使用情况
请参阅此指南,了解如何使用 promise;也可以查看以下示例,了解如何使用 Google Maps JavaScript API 进行异步方法调用。
async 和 await
await 运算符用于等待 promise。该运算符只能在异步函数内使用。
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 对象具有可接受回调函数的 then、catch 和 finally 方法。
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);
- 
目前,promise 只能在 getPlacePredictions()中使用。 ↩