1

I'm trying to create a function which returns a JSON object from an URL. It should work like this:

function getObject(url) {
  // return undefined when the url or json is invalid
  return object;
}

So that I can use it in this way, if I would use the following URL:

var object = getObject('http://ip.jsontest.com/');
console.log('My IP is: ' + object.ip)

The JSON from the example looks like this:

{"ip": "127.0.0.1"}

So the code above should log this:

My IP is: 127.0.0.1

I already tried it with the request module and found this example on StackOverflow:

request.get({ 
  url: 'http://ip.jsontest.com/', 
  json: true, 
  headers: {'User-Agent': 'request'} }, (err, res, data) => {
  if (err) {
    console.log('Error:', err)
  } else if (res.statusCode !== 200) {
    console.log('Status:', res.statusCode)
  } else {
    // data is already parsed as JSON:
    console.log(data)
  }
})

The data is displayed in the console as it should, but I found no way to use the it like in the example I provided above. Is there a way to solve this without callbacks? I read that requests are asynchronous, but I need a synchronus solution.

ShadowEagle
  • 490
  • 1
  • 4
  • 15
  • Node.js runs asynchronous. You could use Promises or Async/Await. – fdelia Sep 07 '17 at 22:06
  • You should not want a synchronous solution. It is never necessary if you embrace asynchronous programming patterns, such as promises. – trincot Sep 07 '17 at 22:06

1 Answers1

-1

No there is no way to do this synchronously. You could look into using the fetch api and an async function if they're supported in your environment.

For example:

async function getMyIpAndDoSomething() {
  const response = await fetch("http://ip.jsontest.com/");
  const object = await response.json();

  console.log(object.ip);
}
SimpleJ
  • 13,812
  • 13
  • 53
  • 93