JavaScript Async Events and How to Handle

Ok, hopefully this post will help someone out there who was struggling with the same thing I was today. It’s a bit of a technical post but I hope it helps highlight the thinking and difference between a language like PHP and JavaScript.

In my mind, I think PHP is a more straightforward program. Things don’t generally happen in async fashion. It’s one step followed by another, followed by another. JavaScript on the other hand can trip people up if you come from a different background. Script execution doesn’t wait for you! haha!

Let me give you an example I was working on today. In general, I have been using IIFE’s to enclose execution and prevent clogging of the global namespace. Well, I often “cheat” or get trapped into wrong thinking when it comes to async execution. What I mean is, I will declare a variable outside of the scope of the ajax function, and then inside the function assign the information I need to the outside function and then go about my merry way.

var clientData;

clientData = someReturnData;


The problem comes if you try to immediately use the return data below this line of code. The value will be undefined because the original script execution will keep going and doesn’t wait for the response from the ajax call.

There are two options (I’m sure there are more, but these are two I can come up with to illustrate my point).

1. Immediately do what you want to do within the async response (notice above this is actually using the Promise structure).
// Do something with the someReturnData here.

2. Encapsulate the code further by wrapping with a callback function. I have chosen this route (and most libraries, etc… use this) because the code I am writing is meant to be used over and over in different spots. My own library I suppose. A “module” if you will. An “object” if you will. You get the idea…. and it looks something like this.

function getClientInfo(someData, callback){

//Then proceed to call this function whenever needed.
getClientInfo(myData, function(returnData){
//Do what I need to with client data in this module.

Now admittedly for me, coming from a C++, PHP background, this all looks a bit screwy to me, but the power is enormous here. Just think, if you have a page with even 4-5 different elements to load, loading them async saves a tremendous amount of time and creates a much more enjoyable front end for the consumer. It modularizes your code. It’s a training issue for your brain to think of code execution in a different way. And despite these languages being curly bracket languages (my term) and similar, there are powerful differences.