0

I just want to return 1 and return 0 at the specified places. I've looked at numerous sources but was unable to solve this issue.

Below is the code :

exports.getLatLng = function(row){
    var attractionId = row['attractionid'];
    var attractionName = row['attractionname'] + ' ' + 
    row['Destination_name'];
    var googleMapsResults; 

    return googleMapsClient.geocode({address: attractionName}).asPromise()
    .then((response) => {
        googleMapsResults = response.json.results[0];
        // console.log(googleMapsResults);
        model.dumpIntoMongo(attractionId, googleMapsResults);
        // var y=tmp[0];
        var latitude = googleMapsResults.geometry.location.lat;
        var longitude = googleMapsResults.geometry.location.lng;
        row["id"] = parseInt(attractionId);
        // delete row['attractionid'];
        delete row['destination_id'];
        delete row['destination_name'];
        delete row['attraction_id'];
        delete row['success'];
        // row["lat"] = latitude;
        // row["lon"] = longitude;

        row["latlon"] = latitude.toString() + "," + longitude.toString();
        exports.indexIntoSolr(row);

        return 1; //return 1

    })
    .catch((err) => {
        console.log(err);
        return 0; // return 0
    });

}
halfer
  • 19,824
  • 17
  • 99
  • 186
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – lolbas Feb 02 '18 at 08:22
  • @lolbas can you please tell what changes I need to make in my code. I really need this up and running. – Akash Prasanna Basabhat Feb 02 '18 at 08:31

2 Answers2

0

The method returns a promise that is pending until it resolves. To get a value you need to attach a continuation to it:

 getLatLng(row).then( result => {
    console.log( result );
 });

This will definitely display 0 or 1 as your internal implementation of the getLatLng looks like it correctly handles both execution paths.

Wiktor Zychla
  • 47,367
  • 6
  • 74
  • 106
0

In case If you want another more clear implementation, you can refer this one.

Here, First write a function which returns some data as promise after certain calculations:

function getSomething(credentials) {

     const {
       name
      } = credentials;

    return new Promise((resolve, reject) => {

      if(everything_as_expected){
           return resolve(some_data)
       }
       else if(some_error){
           return reject(error); 
       }

    });
}

To handle results/Data returned by the function( promisely ), call that previous function:

getSomething(credentials)
        .then((message) => {
          console.log(`${message} got after success.`);
        })
        .catch((error_message) => {
            console.log(error_message);
        });
Abhishek saharn
  • 927
  • 9
  • 23