Node.js access the value of variable from another function - javascript

How do i get the value of myObject.myname, myObject.myage from the function getval? It returns undefined when i console.log it. Btw I'm using node js. Thanks.
var post = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (data) {
console.log('Response: ' + data);
var myObject = JSON.parse(data);
console.log('----------------------------------------------');
console.log(myObject.myname);
console.log(myObject.myage);
console.log('----------------------------------------------');
});
});
function getVal() {
//some code here
console.log(myObject.myname);
console.log(myObject.myage);
}

Declare myObject outside the anonymous function you pass to request (var myObject) instead of inside it. At present it is a local variable.
Call getVal() after the HTTP response has been received (otherwise it won't have been set yet). At present you aren't calling it at all.

There is a scope issue, can you try this instead?
var myObject = {};
var post = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (data) {
console.log('Response: ' + data);
myObject = JSON.parse(data);
console.log('----------------------------------------------');
console.log(myObject.myname);
console.log(myObject.myage);
console.log('----------------------------------------------');
});
});
function getVal() {
//some code here
console.log(myObject.myname);
console.log(myObject.myage);
}

Related

Cannot catch the output of an asynchronous callback into a variable in JavaScript

My code block goes like this :
var http = require("http");
function get_json(url,callback) {
var response = '';
http.get(url, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
response = JSON.parse(body);
callback(response);
});
});
}
// -----------the url---v ------------the callback---v
var mydata = get_json("http://alfreddelivery.cloudapp.net/api/questionnaire/",function fn(item){
console.log(item);
});
I would like to catch the output of get_json function and then assign it to a variable for future options. I tried, var mydata to access the JSON object parsed, but, since the program execution flow hits the mydata variable first, it returns, undefined value for the variable. I have reused this code from stack overflow itself. Please help me for
returning the JSON object to a variable from the async callback in get_json
Use this code base in a JS file and reference it in a web application.
Thanks in advance.

Variable in node.js JavaScript doesn't change

'use strict';
var http = require('http');
function simpleTest() {
var content = '';
http.get("http://google.com/", function (res) {
var html = '';
res.on('data', function (chunk) {
html += chunk;
});
res.on('end', function () {
content = html;
});
});
return content;
}
console.log(simpleTest());
Why variable doesn't change and I get an empty string?
I think that the first function displays variable, and only then execute the http.get. How to make the first code executed and only then the function returns a variable?
It's because the operation is asynchronous. This means that simpleTest returns long before the http.get() response arrives.
Any code that needs the response must be invoked from in the callback. In your case, there could be multiple invocations of the data callback, so you need to handle it inside the end callback.
'use strict';
var http = require('http');
function simpleTest() {
http.get("http://google.com/", function (res) {
var html = '';
res.on('data', function (chunk) {
html += chunk;
});
res.on('end', function () {
console.log(html);
});
});
}
simpleTest();
If you don't want to hardcode the console.log(), you can put it in a function, and pass the function to simpleTest(). This makes it much more generic.
'use strict';
var http = require('http');
function simpleTest(fn) {
http.get("http://google.com/", function (res) {
var html = '';
res.on('data', function (chunk) {
html += chunk;
});
res.on('end', function () {
fn(html);
});
});
}
simpleTest(function(data) {
console.log(data);
});
So here we passed a function to the fn parameter, and invoked the fn parameter inside the end callback.
When we invoke it, we pass the final html value, and the callback receives it in its data parameter.
These are very common patterns, so it would be a good idea to get familiar with them.

Parsing JSON data from a URL

I'm trying to create function that can parse JSON from a url. Here's what I have so far:
function get_json(url) {
http.get(url, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
var response = JSON.parse(body);
return response;
});
});
}
var mydata = get_json(...)
When I call this function I get errors. How can I return parsed JSON from this function?
In case someone is looking for an solution that does not involve callbaks
function getJSON(url) {
var resp ;
var xmlHttp ;
resp = '' ;
xmlHttp = new XMLHttpRequest();
if(xmlHttp != null)
{
xmlHttp.open( "GET", url, false );
xmlHttp.send( null );
resp = xmlHttp.responseText;
}
return resp ;
}
Then you can use it like this
var gjson ;
gjson = getJSON('./first.geojson') ;
Your return response; won't be of any use. You can pass a function as an argument to get_json, and have it receive the result. Then in place of return response;, invoke the function. So if the parameter is named callback, you'd do callback(response);.
// ----receive function----v
function get_json(url, callback) {
http.get(url, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
var response = JSON.parse(body);
// call function ----v
callback(response);
});
});
}
// -----------the url---v ------------the callback---v
var mydata = get_json("http://webapp.armadealo.com/home.json", function (resp) {
console.log(resp);
});
Passing functions around as callbacks is essential to understand when using NodeJS.
The HTTP call is asynchronous, so you must use a callback in order to fetch a resultant value. A return call in an asynchronous function will just stop execution.
function get_json(url, fn) {
http.get(url, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
var response = JSON.parse(body);
fn(response);
});
});
};
get_json(url, function(json) {
// the JSON data is here
});
In this example, function(json) {} is passed into the get_json() function as fn(), and when the data is ready, fn() is called, allowing you to fetch the JSON.

NodeJS return http.request

Hi now I know that NodeJS is asynchronous (which I am still trying to get my head around to be honest).
The problem that I am currently facing is I have attempting to do a http.request to receive some JSON data. This is fine but what I need is to return this data to a variable. I believe I need to do a callback function? (from what I have read up on the matter)
The Code that I currently have:
var http = require('http');
pCLatLng = '';
function postCodeCheck() {
var pCode = {
host: 'geo.jamiethompson.co.uk',
path: "/" + 'SW1A2AA' + ".json"
};
http.request(pCode).on('response', function(response) {
var data = '';
response.on("data", function (chunk) {
data += chunk;
});
response.on('end', function () {
pCJSON = JSON.parse(data);
pCLatLng = pCJSON;
});
}).end();
}
console.log(pCLatLng);
This is obviously outputting "undefined"; I have tried returning the response.on('end') when having return "hi" or anything inside it instead NodeJS outputs the information about the site. If anyone can help with this it would be much appreciated.
console.log(pCLatLng); needs to be inside (or inside something called by) the response.on('end' callback. The value isn't available until that callback is fired.
Try something like:
function postCodeCheck(callback) {
var pCode = {
host: 'geo.jamiethompson.co.uk',
path: "/" + 'SW1A2AA' + ".json"
};
http.request(pCode).on('response', function(response) {
var data = '';
response.on("data", function (chunk) {
data += chunk;
});
response.on('end', function () {
callback(JSON.parse(data));
});
}).end();
}
postCodeCheck(function (pCLatLng)
{
console.log(pCLatLng);
});
You want something like this:
var http = require('http');
function postCodeCheck(cb) {
var pCode = {
host: 'geo.jamiethompson.co.uk',
path: "/" + 'SW1A2AA' + ".json"
};
http.request(pCode).on('response', function(response) {
var data = '';
response.on("data", function (chunk) {
data += chunk;
});
response.on('end', function () {
var pCJSON = JSON.parse(data);
cb(pCJSON);
});
}).end();
}
postCodeCheck(function(pCLatLng) { console.log(pCLatLng); });
Look carefully for the differences before using.
You'll need your postCodeCheck() function to take a callback as well, just like http.request. In the world of async, calling callbacks with results takes a similar role to returning results.

How to return values from functions making HTTP request in node.js?

The getStockValue() function is called from another javascript file in the following way:
var r=require("./stockfile");
var returedData = r.getStockValue());
here returnedData contains only "-START-".
My objective is to get the body object returned from the function, after receiving the response. I've tried putting a return statement into the 'close' event handler, but it didn't work.
How should I do that?
function getStockValue() {
var http = require('http');
var options = {
host: 'in.reuters.com',
path: '/finance/stocks/overview?symbol=RIBA.BO',
method: 'GET'
};
var body = "--START--";
var req = http.request(options, function (res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.on('data', function (chunk) {
body += chunk;
});
res.on('close', function () {
console.log("\n\nClose received!");
});
});
req.on('error', function (e) {
console.log('problem with request: ' + e.message);
});
req.end();
return body + '... recieved';
}
exports.getStockValue = getStockValue;
As this is an asynchronous operation if will return straight away and continue to run in the background, hense why you only receive -START-. You can resolve this with the help of a callback function. Heres how:
Call the function as follows:
r.getStockValue(function(result) {
var returedData = result
//... rest of your processing here
}));
and within the getStockValue function change to this:
function getStockValue(callback) {
...
res.on('data', function (chunk) {
body += chunk;
callback(body);
});
...
}

Categories

Resources