สัญญา

เมธอดแบบอะซิงโครนัสทั่วทั้ง Google Maps JavaScript API จะแสดงผลพรอมิส

การสนับสนุน

การใช้งาน

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

การทำงานแบบไม่พร้อมกันและ 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();

จากนั้นจับ และสุดท้าย

ออบเจ็กต์ Promise มีทั้งเมธอด then, catch และ finally ที่ใช้ฟังก์ชัน Callback

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. ปัจจุบัน Promises ใช้ได้ใน getPlacePredictions() เท่านั้น