o0o0o0o0o
o0o0o0o0o

Reputation: 89

NodeJS request use json data when its recieved

I'm using NodeJS request to get some JSON from a url and then using the JSON object to get data. But I don't know how to use the data, e.g. put it in a variable without getting not defined error because it doesnt wait for the json response to come through. I saw this: https://www.twilio.com/blog/2015/10/asyncawait-the-hero-javascript-deserved.html

But I wont be able to use ES17 features / dont want to do that.

Example 1: Basic Request

var request = require('request');

var url = 'https://api.github.com/users/rsp';

request.get({
    url: url,
    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 {

      var jsonObj = data.html_url
    }
});

console.log(jsonObj) // error not defined

# Example 2: Request promise
require("request/package.json"); // request is a peer dependency. 
var rp = require("request-promise")

var options = {
uri: 'http://api.open-notify.org/astros.json',
headers: {
    'User-Agent': 'Request-Promise'
},
json: true 
};

rp(options)
.then(function (jsonTest) {
    var jsonObj = jsonTest.number;
    console.log(jsonObj)
})
.catch(function (err) {
    // API call failed...
    console.log("failure")
});

So how do I change either of the above examples so you could use the json data outside the request and in later code?

Edit:

I now see that callbacks, promises, async / await are all asynchronous and all either rely on writing code nested in them or code like await that waits for it to return then executes code.

I can see why Promises and async / await are keenly awaited, even if callbacks can do anything, asynchronous code can just get really ugly and unreadable. Thats why I thought it was wrong to nest everything that relies on the callback, but its fine.

Upvotes: 0

Views: 1852

Answers (2)

Sello Mkantjwa
Sello Mkantjwa

Reputation: 1915

For your callback example, anything that needs results from the request has to be run within the callback. See below.

request.get({
    url: url,
    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 {

      var jsonObj = data.html_url
      console.log(jsonObj) // error not defined //You must use the variable here. 
    }
});

The reason is that anything outside that callback will be executed before the callback. In your particular case, the callback will actually only be executed after console.log(jsonObj)

Upvotes: 1

NItin Vaja
NItin Vaja

Reputation: 177

Here is a simple example of how to do this using request without ES6

var request = require('request');
request('http://api.open-notify.org/astros.json', function (error, response, body) {
      var body = JSON.parse(body)
      console.log(body.number);
});

Upvotes: 0

Related Questions