0

I am doing an HTTPS request that stores the data received in a variable. When the request ends all the data will be parsed to JSON and the code will proceed. But I can't type the code outside of the end listener since it proceeds with the code without the request ending. I don't want to type my code in the end listener. What do I do?

const https = require("https");
let templateData = "";
https.get("https://templates.xenon.bot/api/templates/nuAcXSXQc9cM", async (res) => {


    res.on("data", (ch) => {
        // data listener
        templateData += ch;
    }).on("end", () => {
        // end listener
        templateData = JSON.parse(templateData);

    });

}).end();
// rest of code (logs undefined since it doesn't execute after end)
console.log(templateData.creator);

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
invisible boi
  • 106
  • 1
  • 8
  • Canonical: https://stackoverflow.com/q/14220321/3001761 – jonrsharpe Dec 01 '20 at 19:58
  • Look into async/await. You might want to switch to `node-fetch` as a lightweight HTTP library to make this easier, otherwise covert your `https.get` to something that emits a promise. – Evert Dec 01 '20 at 20:02

0 Answers0