เมธอดแบบไม่พร้อมกันในการคืนค่า JavaScript API ของ Google Maps คำมั่นสัญญา
การสนับสนุน
API | เมธอดแสดง "คำสัญญา" |
---|---|
คำแนะนำ | ใช่ |
เมทริกซ์ระยะทาง | ใช่ |
ระดับความสูง | ใช่ |
โปรแกรมเข้ารหัสพิกัดภูมิศาสตร์ | ใช่ |
ภาพที่ซูมสูงสุด | ใช่ |
สถานที่ | ไม่ |
บริการเติมข้อความอัตโนมัติเกี่ยวกับสถานที่ | บางส่วน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
ที่ใช้ฟังก์ชัน 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');
});
รูปแบบ Callback แบบไม่พร้อมกัน
รูปแบบ Callback ยังคงใช้งานได้และได้รับการสนับสนุน
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);
-
ปัจจุบัน Promises ได้รับการสนับสนุนเฉพาะใน
getPlacePredictions()
↩