0

I have an async function that is returning undefined when I console.log the response. The code that calls the function is inside a Lambda function that is async itself hence the desire to use await. The sendRequest function is outside that lambda function though is in the same file.

// main.js
async sendRequest ...

exports.foobar = async ...

Below is the code that calls the function (which is inside another function).

const response = await sendRequest(url)
console.log(response)

sendRequest async function that returns undefined

async function sendRequest (url) {
  let code;
  request({ url, timeout: 20000 }, function(error, response, body) {
    if (error == 'ENOTFOUND' || error == 'ETIMEDOUT') {
      response.statusCode = 500;
    }
    code = response.statusCode
    return {
      code, 
      error
    }
  });
}
joshk132
  • 1,011
  • 12
  • 37
  • code variable is never filled, it always be undefined – mgm793 Jun 11 '20 at 17:17
  • @mgm793 See that I stripped it out by accident when posting. I will edit, though I'd still expect to get an object back so I don't think the missing thing in code is the issue. – joshk132 Jun 11 '20 at 17:18
  • There's a general purpose "promisified" http request here https://stackoverflow.com/a/38543075/294949 – danh Jun 11 '20 at 17:24

1 Answers1

4

You need to return a Promise from sendRequest. request is taking a callback, but that won't work with async-await. The general pattern looks like this

function sendRequest(...) {
   return new Promise((resolve, reject) => {
      // resolve(...) or reject(...);
   });
}
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • Thanks so can I leave the callback with request, I don't think it supports promises which is why I was trying to use callback here. – joshk132 Jun 11 '20 at 17:20
  • @joshk132 correct you have to adapt it to use promises instead. – Daniel A. White Jun 11 '20 at 17:24
  • Thank you for the answer to the question not a guess based off a comment and saying duplicate like someone else has done. Much apperciated – joshk132 Jun 11 '20 at 17:37