You need to sign in to do that
Don't have an account?

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:
Markup
<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 }" /> </aura:component>
Controller
({ handleClick : function(component, event, helper) { helper.handleClick(component); } })
Helper
({ handleClick : function(component) { this.testPromise() .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!
setTimeout() cannot be directly used.