Reputation: 21
I have a problem when I try get response from my function, I'm just start use Promises, so maybe I did something wrong.
When I start my app, I get error then: Cannot read property 'then' of undefined
.
What I did wrong?
Until I start using Promises, everything worked well, after I tried to change app logic it crashed.
My main file below:
/app.js
const request = require('request');
const yargs = require('yargs');
const geocode = require('./geocode/geocode')
const argv = yargs
.options({
a: {
demand: true,
alias: 'address',
string: true,
describe: 'Address to fetch weather for'
}
})
.help()
.alias('help', 'h')
.argv;
geocode.geocodeAddress(argv.a)
.then((res) => {
console.log(res);
},
(error) => {
console.log(error);
})
my geocode file:
/geocode/geocode.js
const request = require('request');
const geocodeAddress = (address) => {
const encodedAddress = encodeURIComponent(address);
request({
url: `https://maps.googleapis.com/maps/api/geocode/json?key=myKey&address=${encodedAddress}`,
json: true
}, (err, res, body) => {
return new Promise((resolve, reject) => {
if(err){
reject('Unable to connect to Google servers.')
} else if (body.status === 'ZERO_RESULTS') {
reject('Unable find any address.')
} else if (body.status === 'OK') {
const lat = body.results[0].geometry.location.lat;
const lon = body.results[0].geometry.location.lng;
const adrs = body.results[0].formatted_address;
const answer = {
lat: lat,
lon: lon,
address: adrs
};
resolve(answer);
}
})
})
};
module.exports.geocodeAddress = geocodeAddress;
Upvotes: 0
Views: 578
Reputation: 21
Code that solve it for me:
const request = require('request');
const geocodeAddress = (address) => {
const encodedAddress = encodeURIComponent(address);
return new Promise((resolve, reject) => {
request({
url: `https://maps.googleapis.com/maps/api/geocode/json?key=myKey&address=${encodedAddress}`,
json: true
}, (err, res, body) => {
if(err){
reject('Unable to connect to Google servers.')
} else if (body.status === 'ZERO_RESULTS') {
reject('Unable find any address.')
} else if (body.status === 'OK') {
const lat = body.results[0].geometry.location.lat;
const lon = body.results[0].geometry.location.lng;
const adrs = body.results[0].formatted_address;
const answer = {
lat: lat,
lon: lon,
address: adrs
};
resolve(answer);
}
})
})
};
module.exports.geocodeAddress = geocodeAddress;
Upvotes: 1
Reputation: 58
it is probably because your geocodeAddress is a constant and not an async function.
blind shot try:
async geocodeAddress (address) {
and like @liam said, try:
return request({...})
Upvotes: 1