+ Start a Discussion

What does $A.getCallback() actually do?

Hello everyone,

I've been trying to wrap my head around $A.getCallback but the only documentation I could find was not very helpful.
https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/js_cb_mod_ext_js.htm says:

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.

So I made a simple component that displays "Hello World" and a button that fakes an async call using promises and setTimeout. Once the promise resolves I update the attribute of the component and the text changed. I was expecting the component not to be rerendered unless I used $A.getCallback(), but it worked fine without it because component is in scope because of the closure created when helper.handleClick() runs. Here is the code:


<aura:component >
	<aura:attribute name="msg" type="String" default="Hello World"/>
	<c:testCmp2 message="{!v.msg}" />
	<lightning:button variant="brand" label="Submit" onclick="{! c.handleClick }" />

	handleClick : function(component, event, helper) {

	handleClick : function(component) {
			.then(function(text) {
				component.set('v.msg', text);
	testPromise : function() {
		return new Promise(function(resolve, reject) {
			setTimeout(function() { 
				resolve('Message Changed') 
			}, 3000);

I'm basically trying to learn how things work by breaking them lol. Can anyone show me an example where some async task does not work when not using $A.getCallback() ?

Thanks in advance!

Check this - http://www.infallibletechie.com/2018/04/agetcallback-usage-for-polling-in.html
setTimeout() cannot be directly used.

Prashant Kumar 148Prashant Kumar 148
You can see the difference while firing the application events. For example if you have used promise and on the resolve of that you have to fire an application event than in such scenarion you will not get the event refrence if you are not using $A.getCallback().