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.
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.
I hope this post was informative and Happy Coding 🙂