Google Maps JavaScript API 전체에서 비동기 메서드는 프로미스를 반환합니다.
지원
| API | 메서드가 프로미스를 반환함 |
|---|---|
| 경로 | 예 |
| 거리 행렬 | 예 |
| 고도 | 예 |
| 지오코더 | 예 |
| 최대 확대/축소 이미지 | 예 |
| 장소 | 아니요 |
| Place Autocomplete 서비스 | 일부1 |
| 스트리트 뷰 | 예 |
사용
Google Maps JavaScript API로 비동기 메서드를 호출하는 방법은 프로미스 사용에 관한 가이드 또는 아래 예를 참고하세요.
async와 await
await 연산자는 프로미스를 기다리는 데 사용됩니다. await 연산자는 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
프로미스 객체에는 콜백 함수를 사용하는 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);
-
현재 프로미스는
getPlacePredictions()에서만 지원됩니다. ↩