0

I try to read and parse Data from an external API with NodeJS, but I am not able to write the parsed Object into something outside of the get() methode.

function Profile(username) {
  const https = require("https");
  const request = https.get(
    `https://teamtreehouse.com/${username}.json`,
    res => {
      let body = "";
      const request = res.on("data", d => {
        body += d.toString();
      });
      res.on("end", () => {
        var profile = JSON.parse(body);
        this.objPropOne = profile;
      });
    }
  );
  this.objPropTwo = request;
}

const objResult = new Profile("chalkers");
console.log(objResult);
Lito
  • 19
  • 4
  • 2
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – ASDFGerte Nov 20 '19 at 17:30
  • It's probably because the request is asynchronous, so when you try to do something outside of the method, the code is running before anything has been returned. You should either do all of your processing inside the callback function or research using promises to handle the asynchronous code. – Sam Walpole Nov 20 '19 at 17:32

0 Answers0