Home > Software design >  How to return from http.get function
How to return from http.get function

Time:11-07

When I run the following, I get the correct console output but the value returned from the function is always 'undefined'

    function get_public_ip() {
        http.get({
            'host': 'api.ipify.org',
            'port': 80,
            'path': '/'
        }, function (resp) {
            resp.on('data', function (ip) {
                console.log(ip.toString());  //outputs ip address
                return ip.toString();      // returns 'undefined'
            });
        });
    }

    async function run() {
        let pubip = await get_public_ip();
        // do stuff with pubip
    }

CodePudding user response:

Make get_public_ip return a promise

function get_public_ip() {
  return new Promise((resolve, reject) => {
    http.get({
      'host': 'api.ipify.org',
      'port': 80,
      'path': '/'
    }, function(resp) {
      resp.on('data', function(ip) {
        resolve(ip.toString());
      });
      resp.on('error', reject);
    });
  });
}

CodePudding user response:

Because http.get returns its data in chunks, and the data event supplies just one of perhaps many chunks, you need to accumulate the chunks and make sense of the aggregated chunks after receiving notification that you have them all, which comes from the end event.

It's also important to concatenate all the buffers before even trying to make sense of the data as a utf-8 string, because the bytes of multi-byte encoded characters may be split into two separate chunks.

The plan is:

  • create a promise, which your function will return
  • on data push the newly arrived buffer into an array
  • on end concat the buffers and decode the utf-8 string, and resolve the promise
  • on error reject the promise
function get_public_ip() {
  return new Promise((resolve, reject) => {
    http.get({
      'host': 'api.ipify.org',
      'port': 80,
      'path': '/'
    }, function (res) {
      let buffers = [];
      res.on('data', buf => buffers.push(buf));
      res.on('end', () => resolve(Buffer.concat(buffers).toString('utf8')));
      res.on('error', reject);
    });
  });
}

CodePudding user response:

Use Like This.

 async function get_public_ip() {
   let data;
await fetch("https://jsonplaceholder.typicode.com/posts").then((res) => {
    data = res;
    return res;
  });
  return data;
}

async function run() {
  let pubip = await get_public_ip();
  console.log("           
  • Related