As a new node programmer, I am struggling to grasp how to retrieve the contents of an HTTP request from a function due to the asynchronous nature of node. Below is a simplified version of my program:
//#1
function getWebsiteData(url) {
var body;
http.get(url, function (res) {
res.on('data', function (chunk) {
body += chunk;
//***At this point, I need 'body' to be returned from this function***
});
});
}
//#2
var dataA = getWebsiteData('website1.com');
var dataB = getWebsiteData('website2.com');
//#3
console.log(dataA + dataB);
My goal is simple: 1: create a function that retrieves data from a site (specifically JSON and XML), 2: call that function from any part of my program, 3: manipulate the data returned by the function.
The placement and calling of callback functions in node.js are causing me quite a headache. Despite studying numerous examples of http.get and callbacks, I have not been able to find one where they mesh together like in my sample code. After a full day of unsuccessful attempts, I am hopeful that seeing how to implement this in my example will finally make it click in my mind (fingers crossed).