In this blog post, Simon Lawrence, an Advanced Salesforce Developer on our delivery team, tackles the subject of the “action.setCallback” method in your Salesforce Lightning Component controllers.
At a first glance, this kind of subroutine/pointer format of coding might be confusing to more strictly Apex/Salesforce developers, but as you will almost certainly encounter Callbacks in any Lightning Component tutorial you read, it is best to start understanding them early.
Fundamentally what you are doing is telling the computer what you want it to do after another function completes – and execution “comes back” to where it was called from (comes back – callback, get it already?) So what you are indeed doing is just passing code around within our code.
The most important area that a Callback will appear in a Lightning Component is during a round trip to the server for an @auraEnabled Apex method call.
Let’s take a look at an example of a simple Callback from a Lightning Component controller:
As this code flows through from top to bottom, one might be forgiven for thinking the code executes in the order 1, 2, 3, 4…? In that, we identify an Apex controller method, and then put its result into a Component attribute.
But what we are actually doing here executes as follows:
1. The setup of a variable “action” – there are a number of properties you could set here.. The minimum being the Apex method we want to call.
2. The callback, here the second parameter is a function itself – all of which is not executed as it is read, but rather stored as an attribute of the action parameter. The contents of which (3) are kind of filed away within action.
4. Then passes our action object into the $A.enqueueAction method, which in this case causes lots of behind-the-scenes code to complete a server request; a key step of which the background code will ask action – what shall we do once the server has finished? To which action replies with the code in 3 – which is finally then executed.
Therefore the order of execution of this code, is more like 1, 2, 4 […], 3.
This can become very confusing if you have other code after 4 which you are expecting to execute in an environment in which the “stuff” in 3 has been completed; it can also be confusing because when the execution thread “comes back” to the callback it is in a different scope to whence-it-came meaning anything you did before 1, or between the end of 3 and 4 will mean nothing to the callback code.
Phew. It’s weird right. But it is an absolutely critical part of programming, especially in such client/server environments as Salesforce. It lets you do lots of very powerful stuff, including clever error handling, and minimises the risks of failed invocations and dropped networks to your business logic.