Mikael Nazaretyan
Mikael Nazaretyan

Reputation: 49

async function returns "undefined"

I have an async function that should return a geocode value:

async function latlng(place){
//var str;
return googleMapsClient.geocode({
    address: place
}).asPromise()
.then((response) => { response.json.results[0].geometry.location
    /*str = response.json.results[0].geometry.location;
    return str;*/
})
.catch((err) => {
    console.log(err);
});
}

When I call it, it returns nothing, but it has a value

I'm calling:

(async function(){
    //location start
    start = await data.latlng(req.body.start);
    //location end
    end = await data.latlng(req.body.end);
})();

Why does it return nothing if it's all fine in the function? How can I solve this problem?

Upvotes: 0

Views: 3077

Answers (1)

Keith
Keith

Reputation: 24181

You are using async / await.. That's great, but for some reason inside your function you decide not to bother.. :)

Also there is no point in catching error in your latlng function, it doesn't make sense as your start / end surely require both to have been valid..

Here is the latlng function simplified, using async / await for what it was meant for.

async function latlng(place){
  const response =
    await googleMapsClient.geocode({ address: place }).asPromise();
  return response.json.results[0].geometry.location;
}

Upvotes: 3

Related Questions