当执行以下功能时,我收到错误消息:
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 362): TypeError: request(...).then is not a function
我不知道此错误消息的原因,但我认为它与我的请求有关。根据{{3}}的“请求 - 承诺”我的代码如果格式正确。
const request = require('request-promise');
addressFunction(lat,lon){
var error = "No Address Data"
var addressExist = true;
return new Promise(
function(resolve){
if(addressExist) {
let apiKey = "API-Key";
let geocodeAddress = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lon + "&key=" + apiKey;
resolve(
request(geocodeAddress).then(res => {
res = JSON.parse(res);
newAddress = res.results[0].formatted_address.replace(/^\d+\s*/, '');
newAddress = newAddress.split(',', 3).join(',').replace(/[0-9]/g, '').trim()
return newAddress
})
);
}
}
);
} }
我尝试传递“选项”参数,例如
var options = {
uri: 'http://www.google.com',
transform: function (body) {
return cheerio.load(body);
}
虽然那仍然没有奏效。
任何人都知道为什么请求...然后抛出错误?
答案 0 :(得分:-1)
你做错了。你需要resolve(newAddress)
而不是整个api召唤承诺
function someFunction () {
return new Promise(function(resolve, reject){
if(addressExist) {
let apiKey = "API-Key";
let geocodeAddress = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lon + "&key=" + apiKey;
request(geocodeAddress).then(res => {
res = JSON.parse(res);
newAddress = res.results[0].formatted_address.replace(/^\d+\s*/, '');
newAddress = newAddress.split(',', 3).join(',').replace(/[0-9]/g, '').trim()
resolve(newAddress);
}).catch(error => {
console.log(error);
resolve('some other values based on logic');
});
} else {
resolve('some other value based on logic');
}
}
);
}