Retrieving User ID Delay

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