JavaScript Asynchronous Callbacks

 

Today we are going to discuss a scenario found often among developers working in the world of JavaScript. Especially developers that don’t come from a language that considers all functions first class objects. This scenario we will be looking at is this:

Issue To Solve

When you have a function that needs to be called after an asynchronous method, how do you handle it? A good example of this is when you need to get a list of data from a RestFul API and based on these results, populate a browser side data table. The problem is that the asynchronous part of an ajax call by nature means that it does not ‘block’ the thread and continues to execute the rest of the code.

Take this as example.

 

In the example above, alert, will always be undefined for two reasons.

1.) At the top, we are not actually initializing the results variable.

2.) Due to the nature of the Ajax call, even though the getData() method is before the alert, the method returns after the alert. If you try it out and put a breakpoint on the anonymous function in the success line, you will see that the success is triggered after the alert. This is called a callback.

What Exactly Are Callbacks?

So what exactly is a “callback”? Essentially, a callback is a ‘promise’ to the caller that when it returns, ‘this method’ will be called. In the above example, the JQuery Ajax method makes a promise that when it returns, the function linked to the success will be called.

Here is an example of what a callback might look like if you didn’t  use JQuery and created one yourself.

If you try this out, you will notice that the “I’ve been hit” gets called and then the “Hit the callback” gets triggered. This is a callback. The method makeCallback() takes in a parameter. This parameter happens to be a method in this case and after the makeCallback is done with the alert, it then triggers the callmeback() method. This is called the callback pattern. By calling the callmeBack method, we are telling whatever calls makecallback() that we promise to call the method it passes in as soon as it is finished with it’s business (in this case the alert). This is because of a concept JavaScript has called “functions as first class objects”. This means that a function can be passed in just like any other parameter.

So How does this solve our problem?

Well, lets take what we have just learned and apply it to the ajax call. Here is the code:

 

So, here we have abstracted the alert for the data returned into a seperate method called callmeback(). This method takes in the result and then alerts the FirstName property of the first result in the array.

Now, the getData() method accepts a method as a property. We are the assigning the promise made by the ajax method to the success promise. By doing this it accomplishes exactly what we need. The ajax call is made, the UI thread is not blocked, so the user isn’t stuck waiting and on return of the call, the alert is triggered via the callback method. For a better understanding of the ajax method and how I knew what was coming back, go here. For some more information on this and other techniques for callbacks such as JQuery promises and anonymous function in JavaScript, see the SO post here

I hope this post was informative and Happy Coding 🙂

Advertisements

About Gregg Coleman

I am Senior-level Software Engineer working primarily these days with .NET. I have a good working knowledge of ASP.NET MVC, Web Forms, WCF web services and Windows Services. I spend much of my time in the Web Services (SOAP and REST) world in my current job designing and implementing various SOA architectures. I have been in the software engineering industry for about 6 years now and will not now nor ever consider myself an "expert" in programming because there is always so much to learn. My favorite thing about designing software is there are always new emerging technologies and something to learn every day! My current job has me spending much of my job on the bleeding edge of technologies and changing gears all the time, so I'm never bored and always challenged. On my spare time I enjoy weight training, reading and venturing to new places near by. Of course programing and learning new technologies are another hobby of mine.
This entry was posted in HTML, HTML Tags, JavaScript, JQuery and tagged , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s