-1
const https = require('https');
async function A() {
    let postData = JSON.stringify({
        "f1": "D1",
        "f2": "D2",
        "encrypted": true
    });
    let options = {
        hostname: "dummyurl1122.com",
        path: "/api/wow",
        method: "POST",
        timestamp: new Date(),
        headers: {
            'Content-Type': 'application/json',
        }
    }

    let chunks = [];
    let reqGetToken = await https.request(options, (resGetToken) => {
        if (resGetToken.statusCode != 200) {
            console.log("***** Error = " + resGetToken.statusMessage);
            return;
        }
        resGetToken.on("data", (d) => {
            chunks.push(d);
        });

        resGetToken.on("end", async () => {
            let output = JSON.parse(await (Buffer.concat(chunks)).toString());
            return output.token; //****** I want this in output
        });
    });
    reqGetToken.on("error", (e) => {
        console.error(e);
    });

    reqGetToken.write(postData);
    reqGetToken.end();
}

let output = await A(); // I want the output but it does not waits for the https response
console.log(output + 2);

When I call the function A it does not waits for the response and goes to next line. How can I make it wait for the output and then go to next line. The function A calls a external POST api and I need its response in output and then execute further lines.

  • 2
    Since when does `https.request` return a promise? – Marc Jan 18 '23 at 15:10
  • Does this answer your question? [nodejs - How to promisify http.request? reject got called two times](https://stackoverflow.com/questions/38533580/nodejs-how-to-promisify-http-request-reject-got-called-two-times) – trincot Jan 18 '23 at 15:16
  • @Marc I was doing R&D to get the desired output. What is the solution and what is wrong? – Vishal Gupta Jan 18 '23 at 15:27
  • 1) `.request` does not return a promise, it returns a `ClientRequest`: https://nodejs.org/dist/latest-v18.x/docs/api/https.html#httpsrequesturl-options-callback 2) You need to wrap your request in a promise. – Marc Jan 18 '23 at 15:46

1 Answers1

0

Since https.request does not return a promise, you can't await it.

See this answer for how to use await with https.

Dr. Vortex
  • 505
  • 1
  • 3
  • 16