Newer Version Available
Return Result for Synchronous Code
An asynchronous method can continue to execute after it returns. JavaScript code often uses the callback pattern to return a result after asynchronous code completes. We’ll describe later how to return a result for an asynchronous action.
Step 1: Define aura:method in Markup
Let’s look at a logParam aura:method that executes synchronous code. We’ll use the c:auraMethodCallerWrapper.app and components outlined in Calling Component Methods. Here’s the markup that defines the aura:method.
The logParam aura:method has an aura:attribute with a name of message. This attribute enables you to set a message parameter when you call the logParam method.
The name attribute of logParam configures the aura:method to invoke logParam() in the client-side controller.
An aura:method can have multiple aura:attribute tags. Each aura:attribute corresponds to a parameter that you can pass into the aura:method. For more details on the syntax, see aura:method.
You don’t explicitly declare a return value in the aura:method markup. You just use a return statement in the JavaScript controller.
Step 2: Implement aura:method Logic in Controller
The logParam aura:method invokes logParam() in auraMethodController.js. Let’s look at that source.
logParam() simply logs the parameter passed in and returns the parameter value to demonstrate how to use the return statement. If your code is synchronous, you can use a return statement; for example, you’re not making an asynchronous server-side action call.
Step 3: Call aura:method from Parent Controller
callAuraMethod() in the controller for c:auraMethodCaller calls the logParam aura:method defined in its child component, c:auraMethod. Here’s the controller for c:auraMethodCaller.
callAuraMethod() finds the child component, c:auraMethod, and calls its logParam aura:method with an argument for the message parameter of the aura:method.
auraMethodResult is the value returned from logParam.
Step 4: Add Button to Initiate Call to aura:method
The c:auraMethodCaller markup contains a lightning:button that invokes callAuraMethod() in auraMethodCallerController.js. We use this button to initiate the call to aura:method in the child component.