1

I'm trying to create a function that parses a json when it gets passed a URL. It parses it and if I try to log it inside the request it works, but I cannot return this value.

function JaySon(){
    request({url: url,json: true}, function (error, response, body) {
        return body;
    })
}

var url ="http://api.geonames.org/findNearbyPlaceNameJSON?lat=51.9877644&lng=-1.47866&username=demo";
var x = JaySon(url);

console.log("json:"+x);

The console just logs "json:undefined", from my understanding it is because console.log gets ran faster than the parsing finishes. How could I go about fixing this issue?

password
  • 11
  • 3
  • 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) – Keith Jun 28 '18 at 12:33

2 Answers2

-1

This is due to the fact that you're not returning anything in your function :

async function JaySon(url) {
  return new Promise((resolve, reject) => {
    request({ url: url, json: true }, function(err, res, body) {
      if (err) reject(err);
      else resolve(body);
    });
  });
}

use it like :

Jayson('your_url').then(data => data)

or with async/await, but then it has to be wrap inside an async function

Fabien Greard
  • 1,854
  • 1
  • 16
  • 26
  • 1
    Unfortunately that will still not work,. :( Turning a callback into a Promise, unfortunately doesn't magically make it await compatible,.. 2 options here, 1.. use say `util.promisify` on the `request`, or 2. use say https://www.npmjs.com/package/request-promise that's done this for you. Or if your really hard core, wrap inside a `new Promise()`.. But even then, what's returned is a Promise, and not the value as the OP seems to think is possible. – Keith Jun 28 '18 at 12:41
  • 1
    Sometimes I should just not try to answer after lunch, i correct my huge mistake (-: – Fabien Greard Jun 28 '18 at 12:47
-1

Another possible reason may also be due to the fact that your function doesn't take any arguments thus there's no request made to the URL you have passed when invoking the function.

Your code should be something like

function JaySon(url){
request({url: url,json: true}, function (error, response, body) {
    return body;
})

}

tonee
  • 1
  • 1