Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use google maps node api using async await

The following is example taken from the Google Maps node module

function doSomeGeoCode() {

  const googleMapsClient = require('@google/maps').createClient({
    key: 'your API key here',
    Promise: Promise
  });

  googleMapsClient.geocode({address: '1600 Amphitheatre Parkway, Mountain 
   View, CA'})
  .asPromise()
  .then((response) => {
    console.log(response.json.results);
  })
  .catch((err) => {
    console.log(err);
  });
}

How do I call the doSomeGeoCode using async and await. Also I need to invoke another function once I have received the response. Please suggest

like image 657
Axesh Ajmera Avatar asked Feb 03 '26 23:02

Axesh Ajmera


1 Answers

You just need to return promisified googleMapsClient and create another method to wait for the response, such as:

function doSomeGeoCode() {
  const googleMapsClient = require('@google/maps').createClient({
    key: 'your API key here',
    Promise: Promise,
  });

  // Return the promise
  return googleMapsClient.geocode({
      address: '1600 Amphitheater Parkway, Mountain View,CA ',
    })
    .asPromise();
}

async function myTest() {
  try {
    // Called the method which returns promise.
    // `await` will wait to get promise resolved.
    const result = await doSomeGeoCode();
    console.log(result);
  } catch (error) {
    // If promise got rejected.
    console.log(error);
  }
}

myTest();
like image 108
S.Mishra Avatar answered Feb 06 '26 19:02

S.Mishra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!