Reputation: 948
I have two problems:
The first problem I can not do asynchronous function:
let address = req.body.merchant_address;
let location = getGeolocation(address);
console.log(location);
async function getGeolocation(address) {
try {
const res = await googleMapsClient.geocode({ address: address }).asPromise();
const location = res.json.results[0].geometry.location;
console.log(location)
return location;
} catch (e) {
return res.status(422).json({
err: err
});
}
}
First it prints Promise { <pending> }
and then only my coordinates, what did I do wrong in the code above?
import maps from '@google/maps';
const googleMapsClient = maps.createClient({
key: 'my key'
});
The second problem. When I build a project, after launching an error Error: Can not find the module '@ google / maps
. I compile the project using babel src --out-dir backend
in the package.json file
. Why doesn't he see "@ google/maps"
?
Upvotes: 0
Views: 116
Reputation: 10882
Regarding the fist problem: The first undefined
is printed by the last line in your code snippet, because it is executed before the callback of geocode
is resolved (asynchronously).
There is the asPromise()
function you can use to get rid of callbacks and make your code synchronous with async/await
like you already started:
try {
const res = await googleMapsClient.geocode({
address: '1600 Amphitheatre Parkway, Mountain View, CA'
}).asPromise();
const location = res.json.results[0].geometry.location;
// your next stuff with location here...
} catch (e) {
console.error(e);
}
Of course, the whole snippet must be called from within an async
function.
Upvotes: 3