Return Result for Asynchronous Code
aura:method executes synchronously. Use the return statement to return a value from synchronous JavaScript code. JavaScript code that calls a server-side action is asynchronous. Asynchronous code can continue to execute after it returns. You can’t use the return statement to return the result of an asynchronous call because the aura:method returns before the asynchronous code completes. For asynchronous code, use a callback instead of a return statement.
Let’s look at an echo aura:method that uses a callback. We’ll use the c:auraMethodCallerWrapper.app and components outlined in Calling Component Methods. Here’s the echo aura:method in the c:auraMethod component.
The echo aura:method has an aura:attribute with a name of callback. This attribute enables you to set a callback that’s invoked by the aura:method after execution of the server-side action in SimpleServerSideController.
The echo aura:method invokes echo() in auraMethodController.js. Let’s look at the source.
echo() calls the serverEcho() server-side controller action, which we’ll create next.
You can’t return the result with a return statement. The aura:method returns before the asynchronous server-side action call completes. Instead, we invoke the callback passed into the aura:method and set the result as a parameter in the callback.
The echo aura:method calls a server-side controller action called serverEcho. Here’s the source for the server-side controller.
The serverEcho() method returns a String.
Here’s the controller for c:auraMethodCaller. It calls the echo aura:method in its child component, c:auraMethod.
callAuraMethodServerTrip() finds the child component, c:auraMethod, and calls its echo aura:method. echo() passes a callback function into the aura:method.
The callback configured in auraMethodCallerController.js logs the result.
The c:auraMethodCaller markup contains a lightning:button that invokes callAuraMethodServerTrip() in auraMethodCallerController.js. We use this button to initiate the call to the aura:method in the child component.
Here’s the markup for c:auraMethodCaller.
See Also