0

I'm new to node JS, Here I tried some code.

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

http.createServer(function (req, res) {
request(header,callback);
 function callback(error, response, body) {
       if (req.url == '/feed') {
           if (!error && response.statusCode == 200){}
               var x = JSON.parse(body);
               console.log(x);
        }
    }
}

I can able to print the JSON data in console. But I want to use that X value in outside of the callback function. I tried return, but no luck. Can you please help me

Matt Fletcher
  • 8,182
  • 8
  • 41
  • 60
pramod m
  • 39
  • 3
  • 1
    You can't. The asynchronous callback will run after everything outside of it. You have to nest your code or use a different method (promises, js async, the caolan/async library, etc) – Matt Fletcher Dec 17 '17 at 22:19
  • The duplicate I flagged this as should give you some great advice about what you're trying to do and why it's not possible. Hope that's of some help :) – Matt Fletcher Dec 17 '17 at 22:24
  • 1
    Yes matt.. Thank you so much – pramod m Dec 17 '17 at 22:25
  • I also like to recommend that people read this book if they want to know more about async and the event loop in JavaScript: https://www.amazon.co.uk/Async-JavaScript-Responsive-Pragmatic-Express/dp/1937785270 – Matt Fletcher Dec 17 '17 at 22:26

0 Answers0