คํามั่นสัญญา

เมธอดแบบไม่พร้อมกันใน Google Maps JavaScript API จะแสดงคำสัญญา

การสนับสนุน

API เมธอดการส่งคืนคำสัญญา
คำแนะนำ ใช่
เมทริกซ์ระยะทาง ใช่
ระดับความสูง ใช่
พิกัดภูมิศาสตร์ ใช่
ภาพซูมสูงสุด ใช่
สถานที่ ไม่ได้
บริการเติมข้อความอัตโนมัติใน Places บางส่วน1
Street View ใช่

การใช้งาน

ดูคู่มือนี้เกี่ยวกับการใช้ Promises หรือตัวอย่างด้านล่างสำหรับการเรียกใช้เมธอดแบบไม่พร้อมกันด้วย Google Maps JavaScript API

ไม่พร้อมกันและรอ

โอเปอเรเตอร์กำลังรอใช้สำหรับรอ 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();

แล้วตามด้วย

ออบเจ็กต์ 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);

  1. ปัจจุบัน Promis ได้รับการสนับสนุนใน getPlacePredictions() เท่านั้น