0

When the function below executed I am getting an error stating:

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 362): TypeError: request(...).then is not a function

I am not aware of the reasoning for this error message, though I assume it has something to do with my request. According the to the documentation for "request-promise" my code if formatted correctly.

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
        })
      );
    } 
  }
);

} }

I've tried passing in an "options" argument such as

var options = {
uri: 'http://www.google.com',
transform: function (body) {
    return cheerio.load(body);
}

Though that still did not work.

Anyone have an idea of why the request...then is throwing errors?

William Merritt
  • 429
  • 1
  • 5
  • 12

1 Answers1

-1

You are doing it wrong. You need to resolve(newAddress) not the whole api call promise

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');
    }
  }
);
}
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60
  • 1
    You are doing it wrong. [You need no `resolve` at all](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it). – Bergi Apr 24 '18 at 20:28
  • I am resolving. @Bergi – Zohaib Ijaz Apr 24 '18 at 20:29
  • This doesn't explain why OP's code doesn't work. As far as I can tell from the documentation for `request-promise`, `request(...).then` should be a function. – David Knipe Apr 24 '18 at 21:09
  • This answer shows a fundamental lack of understanding of how promises work. [like Bergi said](https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it) – Benjamin Gruenbaum Apr 25 '18 at 11:30