What is the usage of $A.getcallback?

370    Asked by ClaudineTippins in Salesforce , Asked on Mar 2, 2023

 I'm a rookie at lightning component development and i'm trying to understand in which situation we should use $A.getcallback. It's not really clear for me when to use it and the explanation in the documentation is not specific enough.

Could someone explain me as i was a 6 years old kid ?

Answered by Diya tomar

Aura, Lightning's runtime, has a "life cycle" that every event goes through. Everything in Aura starts with an event being fired, some controller handling that event, data propagating through any changed attributes, and finally a rendering phase to update the DOM. However, in JavaScript, we're allowed to do things that can step outside of this life cycle, which can break things. As a simple example, consider what happens if you do something like this:

valueChange.evt

demo.app

    {!v.text}

demoController.js
({
    init: function(component, event, helper) {
        setTimeout(function() {
            $A.get("e.c:valueChange").fire();
        });
    },
    updateView: function(component, event, helper) {
        component.set("v.text", "Hello World");
    }
})

Here, we try to fire an event outside the application life cycle, and we subsequently get an error; setTimeout guarantees that we won't be in the life cycle by the time the function is called. In previous API versions, this used to cause significant delay in delivering the event, since outside of the life cycle, no events can occur. We fix that by getting a reference to a function that can kick start the life cycle. We do this by using $A.getCallback:

({
    init: function(component, event, helper) {
        setTimeout($A.getCallback(function() {
            $A.get("e.c:valueChange").fire();
        }));
    },
    updateView: function(component, event, helper) {
        component.set("v.text", "Hello World");
    }
})

Now, instead of crashing, we get to see our message rendered in the app.

The main use for this, and the reason it's called getCallback, is for when you need to use a JavaScript API that is asynchronous. For example, if you're loading a file from the hard drive, or making an API call via XMLHttpRequest, or using Promises (usually). Any time that you want to do something asynchronously, and later be able to update the component values and/or fire an event, you need $A.getCallback.


Your Answer

Interviews

Parent Categories