[SalesForce] Calling aura:method and return value

Is there a way directly return a value from a controller function which is invoked through aura:method?

Example: I have a "super" component with the following markup

SuperComp.cmp:

<aura:component>    
    <aura:method name="getValue" action="{!c.onGetValue}" access="public" />
</aura:component>

SuperCompController.js:

onGetValue : function(component, event, helper) 
{
    return 100;
}

In the application I instantiate the component and I want to call the public method like this

MyApp.cmp:

<aura:application>
    <aura:handler name="init" value="{!this}" action="{!c.onInit}" />
    <c:SuperComp aura:id="myComp" />
</aura:application>

MyAppController.js:

onInit : function(component, event, helper)
{
    console.log(component.find("myComp").getValue());
}

Unfortunately the console output is always undefined (checked that getValue is invoked). So how can I get the value returned from the aura:method?

A workaround would be changing the definition of aura:method by adding an attribute which accepts a javascript callback function and call the callback, but that makes it not so reusable at all.

Best Answer

Methods in Lightning components do not return a value, also came to the same outcome as yourself.

However, I did learn to use and love component events with dynamic event handlers. What you can do from the calling component is fire a component event from within the component you wish to call the method on currently and attach a dynamic event handler for the component finishes processing.

So for example, you can fire an event from where you want to fire the method now like so:

otherComponent.getEvent('provide').fire();

Then also attach a dynamic event handler to listen for a response:

otherComponent.addHandler('responseEvent', component, 'c.handlingControllerAction');

The approach has the benefit of decoupling your components and if you need your other component to do asynchronous work then you can as also the response event would be fired asynchronously. It also allows multiple components to listen out for this event and also react accordingly.

Find more information on the Salesforce help:

https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/js_cb_dynamic_handler.htm

Hope this helps!