0

I am fairly new to Javascript/Node. But I have some programming expierence around Python, Java and C++. However. I can't seem to figure out the scope of the variables. For instance, I've got a variable named x and a method, which gets via a get request a body of a sepecific website. Now I want to store it in another variable.

Dependency I use.

My script:

const request = require('request');

var x;

request('http://www.google.com', function(err, res, body) {
  return this.x = body;
});

console.log(x); // Should return the "body" from the request method.

returns:

undefined
valerius21
  • 423
  • 5
  • 14

1 Answers1

0

You put just var x; at the top scope and assigne the content of x inside of the callback. So what actually happens is

  1. Declare variable x
  2. Start request to google
  3. Console.log(x); which is still undefined / null
  4. Response from request to Google should arrive, then it will assign the response body to x.

You need to understand that it is async.

kentor
  • 16,553
  • 20
  • 86
  • 144