0

i'm new in Node.js, I'm trying to use a variable declared within a Request, but I need to use it outside the Request.Is this possible?.

Sample code:

//stackExample 

var request = require('request')
    cheerio = require('cheerio')
jsonArr = []
request ({
  url: 'http://youtube.com',
  encoding: 'utf8'
  },
  function (err, resp, body){

    if(!err && resp.statusCode == 200){
      var $ = cheerio.load(body);
      $('.yt-lockup-title').each(function(){
        var title = $(this).find('a').text();
        jsonArr.push({
          titulo: title,
        });
      });
    }
    console.log(jsonArr)         //Here Works!
  }
);

console.log(jsonArr)             //Here not :(, I need works here :'(
Valkno
  • 3
  • 3

3 Answers3

0

The issue with above code is that the value in jsonArr is pushed when the request returns from the http call and then injects the value into jsonArr.

You would want to access the value of jsonArr after that call returns.Which you can do by using promises.

Or just a hack using setTimeout.

setTimeout(function(){
 console.log(jsonArr); // use value after time interval  
 },1000);              // you can set this value depending on approx time it takes for your request to complete.

Or use the defered function libraries refer this.

var sequence = Futures.sequence();

sequence
  .then(function(next) {
     http.get({}, next);
  })
  .then(function(next, res) {
     res.on("data", next);
  })
  .then(function(next, d) {
     http.get({}, next);
  })
  .then(function(next, res) {
    ...
  })
Community
  • 1
  • 1
damitj07
  • 2,689
  • 1
  • 21
  • 40
0

You need to wrap the console.log in a callback as follows.

The following code will log [5]

var jsonArry = [];

var test = function(num, callback){
     jsonArry.push(num);
     callback(jsonArry);
};

test(5, function(data){
     console.log(data);
});
frankgreco
  • 1,426
  • 1
  • 18
  • 31
0

Your jsonArr variable only works inside your request function because this wait for the url response, while your outside console.log its executed line by line. You can create a function that will be called inside your anonymous function to use it outside the request function.

var request = require('request')
    cheerio = require('cheerio')
jsonArr = []
request ({
  url: 'http://youtube.com',
  encoding: 'utf8'
  },
  function (err, resp, body){

    if(!err && resp.statusCode == 200){
      var $ = cheerio.load(body);
      $('.yt-lockup-title').each(function(){
        var title = $(this).find('a').text();
        jsonArr.push({
          titulo: title,
        });
        updated()
      });
    }
    console.log(jsonArr)      
  }
);

function updated(){
  console.log(jsonArr)
}
Juan de Dios
  • 2,683
  • 2
  • 20
  • 24