เมธอดแบบไม่พร้อมกันใน Google Maps JavaScript API จะแสดงผล Promises
การสนับสนุน
| API | เมธอดแสดงผล Promises |
|---|---|
| เส้นทาง | ใช่ |
| เมทริกซ์ระยะทาง | ใช่ |
| ระดับความสูง | ใช่ |
| ตัวเข้ารหัสพิกัดภูมิศาสตร์ | ใช่ |
| ภาพที่ซูมได้สูงสุด | ใช่ |
| สถานที่ | ไม่ |
| Places AutocompleteService | บางส่วน1 |
| Streetview | ใช่ |
การใช้งาน
ดู คำแนะนำ เกี่ยวกับการใช้ Promises หรือตัวอย่างด้านล่างสำหรับการเรียกใช้เมธอดแบบไม่พร้อมกัน ด้วย 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
มีเมธอด 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()เท่านั้น ↩