EDIT - This question has been marked as a duplicate of this question, but it is not. My question is not "how to get the response from an async function". My issue is that I am attempting to use one of the solutions explained in that question (using a callback), but I must have the wrong function in my callback and I cannot figure out which.
As a newcomer to both JS and Node, I'm trying to work through incorporating an API like Google Maps into a botkit bot. After reading a number of SO questions on callbacks and watching some videos, I'm starting to figure callbacks out, but in the case below the callback is still returning undefined and I can't figure out why. I've placed the Google Maps call in a callback function which I then call when the appropriate message is heard by the bot.
Given the mapIt function:
let mapIt = function(queryString) {
const mapsApiKey = 'THE_API_KEY';
const googleMapsClient = require('@google/maps').createClient({
key: mapsApiKey
});
googleMapsClient.geocode({
address: queryString
}, function(err, response) {
if (!err) {
formattedAddress = response.json.results[0]['formatted_address'];
//console.log(formattedAddress);
return formattedAddress;
} else {
return 'Maps API Error';
}
});
};
And the calling function:
let getMapsResult = function(suppliedString, callback) {
return callback(suppliedString);
};
It seems like I should be able to use the returned value of mapIt as follows:
controller.hears(
['\\b.*what is the formatted address of\s*([^\n\r?]*)'], ['direct_message', 'direct_mention', 'mention'],
function (bot, message) {
let queryLocation = message.match[1];
bot.say(message, getMapsResult(queryLocation, mapIt));
});
Can anyone help me understand why I'm still getting undefined
with calls to mapIt
?
EDIT - I've tried calling bot.say()
inside the googleMapsClient.geocode()
function, but nothing happens. HOWEVER, console.log does log the Google Maps response:
googleMapsClient.geocode({
address: queryString
}, function(err, response) {
if (!err) {
formattedAddress = response.json.results[0]['formatted_address'];
console.log(formattedAddress);
bot.say(message, formattedAddress);
} else {
return 'Maps API Error';
}
});
calling getMapsResult...
controller.hears(
['\\b.*what time is it in\s*([^\n\r?]*)', '\\b.*what\'s the time in\s*([^\n\r?]*)'], ['direct_message', 'direct_mention', 'mention'],
function (bot, message) {
let queryLocation = message.match[1];
getMapsResult(queryLocation, mapIt);
});