0

After running the code below I get undefined in the console.log.

I am attempting to return a resolved Promise but it fails. There are no errors.

The console output is: getData(): undefined

Can anyone spot my issue?

function getData(){
  var url = 'https://pigfox.com/api/v1/test';
  https.get(url, res => {
      res.setEncoding("utf8");
      res.on('data', data => {
        return new Promise(resolve => {
          resolve(data);
        });
      });
  });   
}

async function go(){
    var rs = await getData();
    console.log('getData(): ' + rs);
}

go();

1 Answer 1

3

You can think of await as "unpacking" a promise. At the moment your getData isn't returning a Promise and so there is nothing to "unpack". Although you do return new Promise within your function, you're actually returning to the inner callback function, not to your outer getData function.

So, you need to wrap your .get method within a Promise, and resolve the data:

function getData() { 
  var url = 'https://pigfox.com/api/v1/test';
  return new Promise(resolve => { // getData returns a promise
    https.get(url, res => {
      res.setEncoding("utf8");
      res.on('data', data => {
        resolve(data); // resolve data which can be "unpacked" using await
      });
    });
  });
}

async function go() {
  var rs = await getData(); // now we can "unpack" the promise
  console.log('getData(): ' + rs);
}

go();
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.