-1

I am working on a small project making request to API and fetch data but compiler not entering into the request.

This is my code :

const https = require("https");
function getUserData(username) {
  let error = "";
  let json_data = {};
  try {
    const req = 
       https.get(`https://xteamtreehouse.com/${username}.json`, res => {
     let data = "";
  if (res.statusCode == 200) {
    res.on("data", in_data => {
      data = in_data.toString();
    });
    res.on("end", () => {
      json_data = data;
    });
  } else {
    error = `An ${res.statusCode} error occured!`;
  }
   });
    req.on("error", e => {
      error = e.message;
    })
  } catch (e) {
    error = e.message;
  }
  if (error)
    return false;
  return json_data;
}
console.log(typeof getUserData("chalkers"))

Output : When I run that code its not showing "string" instead showing "object" that means the get request is not working please help.

Developer K
  • 5
  • 1
  • 9
  • 1
    Possible duplicate of [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) – JJJ Jan 13 '18 at 08:24
  • Still not workiing I used that return json_data in else block – Developer K Jan 13 '18 at 08:25
  • 1
    It's not working because you don't understand the problem. You can't return a value from an asynchronous function. Read *and understand* the duplicate. – JJJ Jan 13 '18 at 08:28
  • Then what can i do in that case sir? – Developer K Jan 13 '18 at 08:30
  • note: almost randomly indented code is hard to read - what your `getUserData` returns is this `let json_data = {};` nothing changes json_data before you return it – Jaromanda X Jan 13 '18 at 08:31
  • I made changes inside get reqest – Developer K Jan 13 '18 at 08:33

1 Answers1

1

I think you might need some JavaScript fundamentals.

const https = require("https");

// this function returns nothing
function getUserData(username) {

  let rawData = '';

  // this request is asynchronous
  https.get(`https://teamtreehouse.com/${username}.json`, (res) => {
    res.on('data', (d) => {
      console.log('hi data transfering');
      rawData += d;
    });
    res.on('end', (d) => {
      console.log('hi end transfered');

      // now deal with the data
      try {

        // the rawData is a string
        console.log('-------------- cut -----------');
        console.log(typeof rawData);
        console.log('-------------- cut -----------');

        // parse it
        const parsedData = JSON.parse(rawData);
        console.log(parsedData);

      } catch (e) {

        // catch the parsing error
        console.error(e.message);
      }

    });
  }).on('error', (e) => {

    // this is the request error
    console.error(e);
  });
}

// run it
getUserData('chalkers')
shrekuu
  • 1,716
  • 1
  • 23
  • 38