-1

stack overflow thread similar

exports.getAddress = asyncHandler(async (req, res, next) => {

    var lon = req.query.lon;
    var lat = req.query.lat;
    var formattedAddress = "";
    var url1 = 'url'

    request(url1, { json: true }, (err, res, body) => {

        if (err) { return console.log(err); }
        formattedAddress = body.formattedAddress;
        console.log(formattedAddress); // string address showing
      });

      console.log(formattedAddress); // string is empty
      
      res.status(200).json({ success: true, data: formattedAddress });
  });

I read the above and many posts but can't understand how can i get the string value outside of the function.

hgb123
  • 13,869
  • 3
  • 20
  • 38
Santhosh
  • 47
  • 7
  • 1
    So take the code that needs that data, and move it to where you know the string will be available. –  Aug 23 '20 at 01:53
  • yeah i did code inside and rename res it worked hav to learn js more. – Santhosh Aug 23 '20 at 02:07
  • Asynchronous programming problems come up in many different languages, and are dealt with differently. For now just get used to the idea that some specific, well-defined functions will require special handling because the end of their execution happens sometime later. This is why there's a callback function in your example. That's just the way of telling the `request` function what you want to do when it eventually finishes. –  Aug 23 '20 at 05:33

1 Answers1

0

You're accessing formattedAddress before request(...) completes, welcome to async world :D

To make it work, you should move res.status(200).json({ success: true, data: formattedAddress }); to inside of request callback, something like this:

exports.getAddress = asyncHandler(async (req, res, next) => {

    var lon = req.query.lon;
    var lat = req.query.lat;
    var formattedAddress = "";
    var url1 = 'url'

    request(url1, { json: true }, (err, res, body) => {

        if (err) { return console.log(err); }
        formattedAddress = body.formattedAddress;
        res.status(200).json({ success: true, data: formattedAddress });
      });
  });
Natan Deitch
  • 556
  • 8
  • 12