0

Consider the following code in Node. The function of web service is a web services provider with input and output parameters. Since this is only an example, there are no input parameters:

var request = require('request');

function mywebservice() {

    request.get(
        'http://www.google.com',
        function(error, response, body) {
            if (!error && response.statusCode == 200) {
                console.log(body);


            }
        }
    );

    return body

}

I need the return the body variable because the web service has to return the variable, but I cannot find a way with making the variable known in the return statement. Even with promises the value of body would be in a function and would not know how to copy to the variable body.

I have already read: How do I return the response from an asynchronous call? and I have not found a solution to get the variable in the response of my webservice.

David
  • 2,926
  • 1
  • 27
  • 61
  • 2
    It is an asynchronous call and you treat it as synchronous. – epascarello Jul 23 '19 at 12:56
  • okay I want a synchronous call and I want to return the value. How do I achieve that? – David Jul 23 '19 at 12:57
  • 1
    You can't. The linked duplicate has a lot of relevant information. – Pointy Jul 23 '19 at 12:57
  • 2
    You can't. That would be time travel – Paul Jul 23 '19 at 12:57
  • @Pointy I have already tried these solutions and I have not found an answer to get the output of body into my response variable. What do you suggest I should do? – David Jul 23 '19 at 13:01
  • @Liam yes probably, I will read it again, thank you – David Jul 23 '19 at 13:03
  • 1
    You can't return the body. Return a Promise instead. – Paul Jul 23 '19 at 13:03
  • 1
    You cannot return the response from an async call. It's impossible. So you need to deal with the async call in an async manner, which covered in great detail in the duplicate. This is an intractable fact. Asking for other options is of no use. There is no other option – Liam Jul 23 '19 at 13:03

1 Answers1

-2
var request = require('request');

this.mywebservice = async () => {
  let body = await this.promisedService()
  console.log(body)
  return body
}


this.promisedService = () => {
  return new Promise( (res, rej) => {
    request.get('http://www.google.com', (error, response, body) => {
      if (!error && response.statusCode == 200) {
        return res(body);
      }
    })
  })
}

this.mywebservice()
Richardson. M
  • 852
  • 2
  • 17
  • 28
  • An explanation of what you've done and why? and what is consuming `this.mywebservice()`? This isn't returning anything – Liam Jul 23 '19 at 13:05