1

I'm new to nodejs and javascript in general. I believe this is an issue with the scope that I'm not understanding.

Given this example: ... ...

if (url == '/'){
  var request = require('request');
  var body_text = ""; 
  request('http://www.google.com', function (error, response, body) {
    console.log('error:', error); 
    console.log('statusCode:', response && response.statusCode);  
    console.log('body:', body);
    body_text=body; 
  });
  console.log('This is the body:', body_text)
  //I need the value of body returned from the request here.. 
}

//OUTPUT 
This is the body: undefined

I need to be able to get the body from response back and then do some manipulation and I do not want to do all the implementation within the request function. Of course, if I move the log line into:

request( function { //here  })  

It works. But I need to return the body in some way outside the request. Any help would be appreciated.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – SLaks May 29 '18 at 21:38
  • Given that this is asynchronous behavior, what then is the correct way to receive a response for processing? The ticket you are referring to is for AJAX I need to retrieve the response here in nodeJS and I fid it really strange I can log the body (which means it was returned in full) yet I cannot assign it to a var and move on. – davidlowellbyrne May 29 '18 at 22:19

1 Answers1

0

You can't do that with callbacks because this will works asynchronously.

Work with callbacks is kind of normal in JS. But you can do better with Promises.

You can use the request-promise-native to do what you want with async/await.

async function requestFromClient(req, res) {
    const request = require('request-promise-native');
    const body_text = await request('http://www.google.com').catch((err) => {
      // always use catches to log errors or you will be lost
    })

    if (!body_text) {
      // sometimes you won't have a body and one of this case is when you get a request error
    }
    console.log('This is the body:', body_text)
    //I need the value of body returned from the request here.. 
}

As you see, you always must be in a function scope to use the async/await in promises.

Recommendations:

  1. JS the right way
  2. ES6 Fetures
  3. JS clean coding
  4. More best practices...
  5. Using promises
Marlom
  • 578
  • 5
  • 15