Retrieving User ID Delay

I made a command that retrieves the user id and prints it in the console. I used my main twitch account and I created another to test it but there seems to be a delay. Here is my code.

if(messageArray[0] === "!test"){
        requestOptions.url = "" + "?login=" + user.username;
        request.get(requestOptions,(error, response, data) => {

        if(error) throw error;
        obj = JSON.parse(data);
        userID =[0].id;

When I run this command on my main account it will first print undefined, but then after a second try it prints my id properly. When I test it on my second account (immediately after the last attempt) it prints out the user id for my main account and not the one I want.

Is this an issue on my end? Or is this just how twitch handles requests?

The issue you’re having is that because HTTP requests are asynchronous.

Your code is sending the request, and while waiting for a reply it moves on to the next thing which is the console.log(userID); which is undefined at first, and then when you receive a response to your request your callback function runs where you then assign a value to obj and userID.

The reason it works the second time is because just like before it’s running console.log(userID) before the request even receives a response, and this time it’s not undefined because your callback function from the last request assigned it a value.

What you need to do when working with asynchronous functions is to wait until the function is complete before attempting to do anything with the data. In your example this could mean moving the console.log(userID) into the callback of the request. (You may also want to move where you define obj and userID into the callback too so you limit their scope, otherwise you may get odd issues like you’ve just experienced where different functions may be erroneously using data from an object that’s different from whats expected)

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.