Home > OS >  Unable to get the variable value outside the http call
Unable to get the variable value outside the http call

Time:10-25

I have written below code to get the response data chunk in the variable called outBody, but it is showing undefined. Any suggestions please?

var options = {
  host: 'jsonplaceholder.typicode.com',
  port: 80,
  path: '/todos/1'
};

var outBody;

http.get(options, function(res) {
    console.log("Got response: "   res.statusCode);

    res.on("data", function(chunk) {
        outBody = chunk;
    });
}).on('error', function(e) {
    console.log("Got error: "   e.message);
});

console.log(outBody);

I actually want to use the variable outBody outside the http request. How can I use it?

CodePudding user response:

Your code is showing undefined, because your code is a asyncronous code and you are logging data synchronously.

A simple fix is that put your console.log inside the data event listener like this


    res.on("data", function(chunk) {
        outBody = chunk;
        console.log(outBody);
    });

and if you want to use the outBody variable outside the http.get then you either has to use promises or a callback function inside another event listener called end , which fires when the response is completed.

Like this

using CallBack :-

//Your code
res.on("data", chunk => {
    outBody  = chuck
});

res.on("end", () => {
    // this event fires when the response body is completely loaded ...
    myFunction(outBody); // pass the respone body to your callback function
}
// remaing code 

Wanna learn how to deal with this problem again, then learn about async / await and promises on internet

OR

Using promises / async await :-

const options = {...}
var outBody = "";
const req = new Promise( (resolve, reject) => {
    http.get(options, res => {
        res.on("data", chunk => { outBody  = chunk });
        res.on("end", () => resolve(outBody));
        res.on("error", console.error);
    });
});

req.then( data => {
  myFunction(data);
})
.catch(err => console.error(err));

// or u can try async / await 

(async function (){
    const data = await req;
})();

Note : You had done a mistake i.e., inside the data event listener you overwrite the outBody with the new chunk. It is a mistake because the http class loads the response in chuck which means parts. It means you are losing data , I also fixed it by adding = in place of outBody = chunk, it simply appends the new part the older part which gives you the complete response body...

Still confused about the promises and async / await , then them here

CodePudding user response:

The http request is asynchronous, the reason why console.log is logging undefined is because you log the result of the request before the request is done, only after the request is done outbody gets the value of chunk. In order to access the outbody value you should write the console.log inside the callback block which is called right after the data is returned from the request like this:

http.get(options, function(res) {
console.log("Got response: "   res.statusCode);

res.on("data", function(chunk) {
    outBody = chunk;
    console.log(outbody)
});
res.on("error",e=>{
  console.log("Got error: "   e.message);
})
})
  • Related