如何修复:“无法读取未定义的属性‘then’”
2019-01-08
571
当我尝试从函数获取响应时遇到问题,我刚开始使用 Promises,所以也许我做错了什么。
当我启动我的应用程序时,我收到错误:
无法读取未定义的属性“then”
。
我做错了什么?
在我开始使用 Promises 之前,一切都运行良好,在我尝试更改应用程序逻辑后,它崩溃了。
我的主要文件如下:
/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);
})
我的地理编码文件:
/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;
2个回答
可能是因为您的 geocodeAddress 是一个常量,而不是一个异步函数。
盲拍尝试:
async geocodeAddress (address) {
就像@liam说的,尝试:
return request({...})
Joel Rodrigues
2019-01-08
为我解决问题的代码:
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;
Valentin Mohis
2019-01-08