Friday 9 June 2017

Node.js Asynchronous return from HTTP request

I'm very new to JS and node. I am trying to return a variable from an asynchronous http request, and I recognize that the problem is the async nature of the call, but cannot figure out how to make a very simple code snippet function despite reading multiple tutorials.

Can someone please mark this up such that it works and I can digest it and modify for my own use? Should I be using the async library? I've taken a couple of attempts and haven't been able to make that work.

var request = require('request');
a = 0;

a = foo();
function foo() {
   var num = 1;
   request('http://www.google.com', function (error, response, body) {
        // console.log('error:', error); // Print the error if one occurred
        //console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
        //console.log('body:', body); // Print the HTML for the Google homepage.
        num = 3;
        return callback(num);
    })
   return num;
}

console.log(a);


via dave

No comments:

Post a Comment