0

Still learning node. Based upon the following: https://github.com/request/request

var request = require('request');
request('http://www.google.com', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body) // Show the HTML for the Google homepage.
  }
})

I wish to create the above as a reusable block of code so thought I'd wrap it in a function passing the URL as a parameter such as:

var request  = require('request');
var URL;

var request = require('request');
request('http://www.google.com', function (error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log(body) // Show the HTML for the Google homepage.
    }
})

function fetchURL (URL) {
    request(URL, function (error, response, body) {
      if (!error && response.statusCode == 200) {
        return body;
      }
    });
};

var a = fetchURL('http://www.google.com');
console.log(a);

This works however I am unsure of whether "return body" is needed as it also works without this line. Happy to received comments on my coding style too as it's all new to me.

Dercni
  • 1,216
  • 3
  • 18
  • 38
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Quentin Aug 06 '16 at 07:22

1 Answers1

0

The pattern in Node is to provide a callback as an argument to an asynchronous function. By convention, this callback function has error as its first argument. For example:

function fetchURL(url, callback) {
    request(url, function(error, response, body) {
      if (!error && response.statusCode == 200) {
        callback(null, body);
      } else {
        callback(error);
      }
    });
};

fetchURL('http://www.google.com', function(err, body) {
    console.log(body);
});

Note that in your snippet, return body; is a return from the anonymous callback function passed into fetchURL(). fetchURL() itself returns nothing.

edwinbs
  • 525
  • 3
  • 14