0

OilĂ , I'm a beginner with nodejs and I am using it to create a telegram bot. This is my code:

const Geolocation = (req) => {
        var address = "15 Freedom Way, Jersey City, NJ 07305, United States";
        let msg = "";

        let nodeGeocoder = require('node-geocoder');
        let param = {
            provider: 'openstreetmap'
        };
        let geoCoder = nodeGeocoder(param);
        geoCoder.geocode(address)
            .then((res) => {
                msg = res[0].streetName;

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

        console.log(msg);

        return UTILS.formatDialogflowResponse(
            msg,
            []
        );
    }

I would like it to keep the streetName so that I can send it as a return response in UTILS.formatDialogflowResponse

I tried to write to a file and then read it just before sending, but every time it tends to first read the file, thus creating an error, and then write on it

pergy
  • 5,285
  • 1
  • 22
  • 36
kekko4000
  • 37
  • 4

1 Answers1

0

You must first learn about Promise and async await in Nodejs.

For short, you can try this

const Geolocation = async (req) => {
var address="15 Freedom Way, Jersey City, NJ 07305, United States";
let msg="";

let nodeGeocoder = require('node-geocoder');
let param = {
  provider: 'openstreetmap'
};

let geoCoder = nodeGeocoder(param);
await geoCoder.geocode(address)
  .then((res)=> {
    msg=res[0].streetName;
    
})
.catch((err)=> {
  console.log(err);
});

console.log(msg);

return UTILS.formatDialogflowResponse(
    msg,
    []
);}
hungtran273
  • 1,180
  • 9
  • 11