AJAX Asynchronicity and Functions Within Functions 😖

Currently working on the twitch tv project and I am having trouble since I am doing two AJAX calls and the data is not going into my variables at the right time it seems.

I have a function initUser() which is supposed to initialize the user by first running another function called getData() which basically gets the user’s offline data and assigns this data to the global object ****userObj. Then another function is run called onlineStatus() which checks if a user is currently streaming by checking if data.stream is null or not. Then finally $().append is used to display the data on the screen.

Problem is I am getting undefined for everything and I know that it has to do with the data from the AJAX request not getting back in time, maybe I’m wrong but it feels to be the case. I have been staring at the code for hours trying to figure this out or trying to refactor it without success.

Would appreciate any help.

I think I struggled with similar problem and I solved it by using .then(). And then from the .then success callback, I could do the next API call. I’m just learning all this stuff and so I’m not sure if this is best solution or if there are other options.

If you like, feel free to check out my project https://codepen.io/barbarap/pen/gGeGMb

Hey, thanks for the reply. I was actually looking into trying to understand .then(). It initially seemed like something that would work for me, I just don’t fully understand it yet. Need to read up on it more. Thanks for the link to your project. I was looking at your code to try and see how you made it work.

I refactored the code in the way that you suggested. Looks like I’m one step closer to my intended result. I am no longer getting undefined for everything. Problem now is that the way the data is being displayed is inconsistent.

Mostly what I am seeing is the same user being displayed over and over. Occasionally there might be 2 or 3 users displayed, but again, they are repeated.

I am looking at the code and it seems to me that either something is not yet right with my onlineStatus() function or that the way that I am handling the userObj is incorrect.

Thanks a lot, code is working as intended now!