Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having trouble using async await with Google Maps Geocode API

I'm using the Google Maps Geocode API and attempting to use async await. I've defined several functions for handling the request:

function googleGeoCode(address) {
  const googleMapsClient = require('@google/maps').createClient({
    key: 'googleMapsApiKeyGoesHere',
    Promise: Promise
  });

  return googleMapsClient.geocode({ address: address }).asPromise();
}

async function getGeoCode(address, errors, res) {
  try {
    const result = await googleGeoCode(address);
    return result;
  } catch (error) {
    errors.googleMapsClient = error;
    return res.status(400).json(errors);
  }
}

I then use the getGeoCode function in my express route:

const geoResponse = getGeoCode(req.body.address, errors, res);

The await portion of the function is not working correctly. If i console log geoResponse I get Promise { <pending> }

I'm new to using async await and I'm not sure if I am doing something incorrect here. Any help is really appreciated!

like image 657
nflauria Avatar asked Oct 23 '25 18:10

nflauria


1 Answers

An async function always returns a promise or wraps the return value into promise,you have to resolve the promise like this

 const geoResponse = getGeoCode(req.body.address, errors, res);

    geoResponse.then((result)=>{

    console.log(result)
    }).catch((err)=>{
     console.log(err);
    })
like image 76
Shubh Avatar answered Oct 26 '25 10:10

Shubh



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!