Using Promises
Request Woosmap services asynchronously through Map JavaScript API
Handling Asynchronous Operations
The Woosmap Map JavaScript API provides a convenient way to manage asynchronous service calls. Each service operation is associated with an asynchronous function that initiates the operation and returns a Promise object. You can attach handlers to this Promise object, which will be executed when the operation is either successful or unsuccessful.
The services currently implemented in Map JS that support Promises are:
Any error that occurs during the execution of the service call is captured and handled as a rejected Promise.
It is then passed in the catch
callback as an APIError
object.
Working with Promises
The Promise object includes then
, catch
, and finally
methods, each accepting callback functions.
In the following example, a promise
is returned that is either fulfilled with a Localities geocode response
object
or rejected with
an error
object. This approach allows for separate callbacks for success and failure scenarios, rather than a single
callback responsible for error detection.
const localitiesService = new woosmap.map.LocalitiesService();
const latLng = {lat: 43.610, lng: 3.876};
const promise = localitiesService.geocode({latLng});
promise
.then((response) => {
console.log(response.results);
})
.catch((error) => {
console.log(error);
})
.finally(() => {
console.log('done');
});
Using Async and Await
You can use the async/await
pattern in your calls to the Map JS API.
The await
operator is used to wait for a Promise. It can only be used inside an async
function.
The following example uses async/await
to reverse geocode a location using LocalitiesService
.
const runLocalitiesGeocode = async () => {
const localitiesService = new woosmap.map.LocalitiesService();
const latLng = {lat: 43.610, lng: 3.876};
try {
const response = await localitiesService.geocode({latLng});
console.log(response.results)
} catch (error) {
console.error(error);
}
};
runLocalitiesGeocode();