0

I have a function that runs a GET request from a remote server and brings back the data. I can see the data on the console when I log it but I can't seem to get it as a return value.


async function getUserDetails(telephone){

var full_name = '';

https.get('https://this.server.com/public?telephone', (resp) => {
                 

                  // A chunk of data has been received.
                  resp.on('data', (chunk) => {
                    data += chunk;
                    JSON.parse(data, function (key, value) {
                      if (key == "12") {
                        full_name+=value;
                      }});
                  });

                  // The whole response has been received. Print out the result.
                  resp.on('end', () => { 
                        console.log("FULL NAME "+full_name);
                  });

                  // An error occurred. Print out the message
                }).on("error", (err) => {
                  console.log("Error: " + err.message);
                });

  return full_name;
}

I tried setting the data value to a User MODEL on the on('data') but when I try to retrieve the value it returns UNDEFINED.

  • 1
    Since `https.get` doesn't return a promise, you probably wouldn't use an `async` function for this. But you can still have a function that returns a promise (like an `async` function does), by wrapping the callback-style `https.get` code in a promise as described in [these answers](https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises). – T.J. Crowder Nov 30 '22 at 08:28

0 Answers0