0

I have this code that makes a request and returns an ID if successful if not it will return undefined. I tried to use "deasync" library, but unfortunately the snippet tries to find out by if its undefined, So I get stuck into the loop. Anyway I could make the request synchronous.

var panorama = require('google-panorama-by-location')

var location = [ 51.50700703827454, -0.12791916931155356 ]
panorama(location, function (err, result) {
  if (err) throw err

  // pano ID
  console.log(result.id)

  // actual latitude, longitude
  console.log(result.latitude)
  console.log(result.longitude)

  // other details from Google API
  console.log(result.copyright)
})

Using deasync:

function AnticipatedSyncFunction(panorama,location){
    var ret;
    panorama(location, function (err, result) 
    {
        if (err){
            throw (err);
            ret = "test";
        } 
        else 
        {
            ret = result.id;
        }
    })
    while(ret === undefined) {
        require('deasync').runLoopOnce();
    }
    return ret;
}
MasterWizard
  • 767
  • 2
  • 13
  • 42
  • IMHO `deasync` is not a good solution for any use case. Why not just use callbacks/promises/etc.? – mscdex Aug 29 '16 at 15:29
  • You cannot ever synchronously return a value that is obtained asynchronously. Javascript simply doesn't work that way. You have to write async code and use a callback or promise to return the result. See the selected answer to the question yours was marked a duplicate of for several ways to do that. – jfriend00 Aug 29 '16 at 17:01

0 Answers0