getCallback()

Use $A.getCallback() to wrap any code that modifies a component outside the normal rerendering lifecycle, such as in a setTimeout() call. The $A.getCallback() call ensures that the framework rerenders the modified component and processes any enqueued actions.

Don't use $A.getCallback() if your code is executed as part of the framework's call stack. For example, your code is handling an event or in the callback for an Apex controller action.

Run async operations with a $A.getCallback() wrapper. For example, use setTimeout() and setInterval() with $A.getCallback(). Use Promise resolve or reject handlers with $A.getCallback().

When using $A.getCallback(function callback) with a Promise, the function runs after the Promise resolves. For example:

1({
2    getUser : function(component, event, helper) {
3        
4        // Call helper to get the Promise object
5        var userPromise = helper.fetchUserData();
6        
7        // Set the Promise object into an attribute (v.userPromise)
8        component.set("v.userPromise", userPromise);
9        
10        // Use .then() with the Promise that's retrieved via component.get()
11        // The Promise resolves and its result is passed to the function
12        component.get("v.userPromise").then(
13            
14            $A.getCallback(function(result) { 
15                
16                // 'result' is returned object from the helper
17                var userName = result.name; 
18                var userId = result.id;
19                
20                // Use the data to update a component attribute
21                component.set("v.userName", userName);
22            })
23        ).catch($A.getCallback(function(error) {
24            // Handle any potential errors during the promise resolution
25            component.set("v.userName", "Error fetching data.");
26            console.error("Promise rejected:", error);
27        }));
28    }
29})

Signature

getCallback (function callback)

Parameters

callback
Type: function
The method to call after establishing an Aura context.

Sample Code

Use $A.getCallback() with component validity check.

1window.setTimeout(
2    $A.getCallback(function() {
3        if(cmp.isValid())
4        cmp.set("v.value", data);
5    }), 5000
6);

Use Promise handling with Aura lifecycle management.

1promise.then($A.getCallback(function(result) {
2    if(cmp.isValid())
3    helper.process(result); 
4    }
5));