Reputation: 79
I am a newbie in Node.js. I want to store the value of body.xyz in variable A. and want to access from the outside the request like i did in at end of the code. Here is my code, How I can set the variable value. It is showing null value at the end of program.
var request = require('request');
URL = "http://aaaa.com/api.php"
// Decleare the variables
var A = null;
PARAMS_0 = {
'a':"query"
}
request.get( {
url: URL,
qs: PARAMS_0
},
function(error, response, body) {
body = JSON.parse( body)
A = body.xyz
}
);
console.log( A )
Upvotes: 1
Views: 4358
Reputation: 206
Just try to put Console.log statement inside the callback, if you are not getting the output. Bacause node's asynchronous behaviour makes it possible that a statement written after another statement will get executed / produce output first that is what i think is happenning with your case.
Hope it helped.
Upvotes: 0
Reputation: 787
It's showing null because callback from request.get
is executed after console.log
, if you would add console.log
inside of callback you would see the result.
Install https://github.com/request/request-promise
Try this one:
var request = require('request-promise');
URL = "http://aaaa.com/api.php"
PARAMS_0 = {
'a':"query"
}
(async () => {
const A = await request.get( {
url: URL,
qs: PARAMS_0
});
console.log( A );
})();
Read this article: https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-promise-27fc71e77261
It perfectly explains idea of promises, and how you should work with them.
Upvotes: 1