0

I am learning NodeJS, and I wrote a simple function that makes an https get request and returns the response in a promise, which then gets logged. However, I get no response at all. Can anyone tell me why?

funcs.js

const https = require("https")

const makeGetReq = async (url) => {
    var response = ""
    https.get(url, (res) => {
        res.on("data", (chunk) => {
            response += chunk
        })

        res.on("end", () => {
            return response
        })
    }).on("error", (err) => {
        return err
    })
}

module.exports = { makeGetReq: makeGetReq }

main.js

const { makeGetReq } = require("./funcs")

makeGetReq("https://www.google.com")
    .then((response) => {
        console.log(`${response}`)
    })

OUTPUT:

undefined
Sohail Saha
  • 483
  • 7
  • 17
  • 1
    you never actually returned anything from `makeGetReq`, therefore the promise it will return because it's `async` will contain an undefined value. There's no real value in making makeGetReq `async`, either way you need to promisify the callback-based function it is calling. – Kevin B Aug 03 '21 at 17:32
  • 1
    `return response` is place in the `res.on(...)` callback but only returns from the callback. It does return from `makeGetReq(...)`. – 3limin4t0r Aug 03 '21 at 17:33
  • 1
    You can convert "old" callback interfaces to uses promises, using the [Promise constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#creating_a_promise_around_an_old_callback_api). Here is an [example using your scenario](https://gist.github.com/3limin4t0r/c0d311fe9cfd81e300c9277823b14883) – 3limin4t0r Aug 03 '21 at 17:50
  • You are exporting `makeGetReq` before it is defined. First the export happens, then the function that defines `makeGetReq` completes. Welcome to the world of asynchronism :) – Jeremy Thille Aug 03 '21 at 18:02
  • @Kevin B Thank you, now I get the point. Absolutely correct! I never returned anything from the function itself. – Sohail Saha Aug 03 '21 at 18:05
  • @3limin4t0r Thanks for the example. I get it now. – Sohail Saha Aug 03 '21 at 18:06

0 Answers0