Pages - Menu

Fetch then Promise by Google Geocoder Example

Scope

Our store locator supports searching by post code or suburb names.


However, our Demandware instance only have stores information by post code. In order to retrieve store information by suburbs, firstly we make an ajax call to the Google Maps Geocoding API to find out the post code by suburb. Then, use this information to search for stores.

All of the above are javascript driven by React dispatches. In our console log, we found that the code is fetching the getStoreUrl before the Google API callback our site which is incorrect. The timeline looks like this.


Technical

The Goal: After we called geoCoder(), we need to wait for Google API callback() before calling getStoreUrl().

To achieve this, we will wrap the Google API call within a Promise object. For simplicity, I stripped out some of our custom logic and our code looks like this.

export const geoCoderPromise = (address) => {
 console.log ('geoCoderPromise() called.')
 
 var geocoder = new google.maps.Geocoder();
 
 return new Promise(function(resolve, reject) {
  
   geocoder.geocode({'address': address}, function(results, status) {
      console.log ('geoCoderPromise Callback() called', results)
      
      if (status == google.maps.GeocoderStatus.OK && results[0]) {
       resolve(results[0]);
      } else {
       reject(status);
      }
   })
 })
}

We use 'then' to chain up the Promise objects chronologically.

export export const fetchStores = () => {
  console.log('dispatch action - fetchStores')
   
  return dispatch => {
    return geoCoderPromise(address)
      .then(result => fetch(getStoreUrl(result)))
      .then(response => console.log(response.text()))
  }
}

Looking at the console log, the execution sequence is now correct. Firstly we ask Google what is the post code for Paddington, then we past 2021 as a parameter to our getStoreUrl to generate the url and then dispatch a fetch().



No comments:

Post a comment