Search code examples
node.jsjsonvariablesreturnundefined

JSON variable returns Undefined


Sorry for the inconvenience, I am a newbie in Node. I am trying to store a json in "usersData" variable so I want to use it later in another functions. The problem is that if I test the variable with console.log inside the "if" it returns to me results, but when trying to show the variable outside the request subfunction, it comes out 'undefined'. I have declared the global usersData variable as shown below. Thank you.

var usersData;

function getAllUsers(){
  request({url, json: true}, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      usersData = body
      //console.log(usersData)  //Here returns a value
    }
  });
  console.log(usersData)  //here returns undefined
}

Solution

  • request is asynchronous method, so if you want to use its result later in another functions, should handle that in second parameter callback. i.e

    var usersData;
    
    var handleUserData = function() {};
    
    function getAllUsers(){
      request({url, json: true}, function (error, response, body) {
        if (!error && response.statusCode == 200) {
          usersData = body
          //console.log(usersData)  //Here returns a value
    
          // use results in another function
          handleUserData(body);
        }
      });
    }
    

    or use Promise

    function getAllUsers() {
      return new Promise(function(resolve, reject) {
    
        request({url, json: true}, function (error, response, body) {
          if (!error && response.statusCode == 200) {
            usersData = body
            //console.log(usersData)  //Here returns a value
            resolve(body);
          } else {
            reject(error);
          }
        });
    
      });
    }
    
    // handle `usersData`
    getAllUsers().then(body => {
      handleUserData(body);
    });