0

Well I had a bit problems

function getId(username){
const https = require("https")
let id = ""
let data = ``
https.get(`https://api.roblox.com/users/get-by-username?username=${username}`, (response) =>{
    response.on('data', (chunk) => {
        data += chunk;
    })
    response.on('end', () =>{
        if(data){
          id = JSON.parse(data).Id
        }
    })
})
.on('error', (error) => {
   console.log(error)
})
return id
}

So my goal here to use getId("IHZAQSTORM33") and expected result, it will return user id (1684676332). but instead, it give me (""). It give me a colons
yes I'm trying to connect to roblox api.

IHZAQSTORM33
  • 102
  • 9
  • Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Kevin B Dec 14 '21 at 17:16
  • @Kevin B well I'm not using jquery, so yep it still a problem – IHZAQSTORM33 Dec 15 '21 at 05:22
  • You'll want to learn about how asynchronous programming works. When your function exits, `id` does not yet have a value.. – Mike Christensen Dec 15 '21 at 05:23

1 Answers1

2

Use promise to return the response object as shown in the code.

  1. You can also refer to link for the comment by nkron:

Where is body in a nodejs http.get response?

function getId(username) {
  const https = require('https');
  let id = '';
  let data = '';
  const url = `https://api.roblox.com/users/get-by-username?username=${username}`;
  return new Promise((resolve, reject) => {
    https
      .get(url, (response) => {
        response.on('data', (chunk) => {
          data += chunk;
        });
        response.on('end', () => {
          resolve(data);
        });
      })
      .on('error', reject);
  });
  //return id
};


(async () => {
  const responseObject = await getId('IHZAQSTORM33');
})();

  1. For more on async and await, refer this link: await is only valid in async function