In the Lightning Component Developer Guide you can find that Promises can be used in Lightning Components and what special things we need to care for to make them work. But there is no fully working example on how to implement and use them.
Let's say we have 3 @AuraEnabled Apex methods we want to call asynchronously after each other using the output of the first as input parameter of the second and so on.
public class elfApexCascade {
@AuraEnabled public static Object myServerSideAction_1(String input) {
return input+'.Apex1';
}
@AuraEnabled public static Object myServerSideAction_2(String input) {
return input+'.Apex2';
}
@AuraEnabled public static Object myServerSideAction_3(String input) {
return input+'.Apex3';
}
}
The logic is very simple: it concatenates only the strings and calling the first method with an initial "START"
we would expect something like this as result of the last Apex call: "START.Apex1.Apex2.Apex3"
The component itself has only one button to start the cascaded execution.
<aura:component controller="elfApexCascade" implements="flexipage:availableForAllPageTypes,force:hasRecordId" access="global" >
<button onclick="{!c.onclick}">Apex</button>
</aura:component>
Now invoking that Apex in good old xmas-tree-style looks like this in the controller:
onclick : function(cmp, evt, hlp) {
var call1 = cmp.get("c.myServerSideAction_1");
call1.setParams( { input : 'START' } );
call1.setCallback(null,function(res) {
if(res.getState()=='SUCCESS') {
console.log('Call 1 : ', res.getReturnValue() );
var call2 = cmp.get("c.myServerSideAction_2")
call2.setParams( { input : res.getReturnValue() } );
call2.setCallback(null,function(res) {
if(res.getState()=='SUCCESS') {
console.log('Call 2 : ', res.getReturnValue() );
var call3 = cmp.get("c.myServerSideAction_3")
call3.setParams( { input : res.getReturnValue() } );
call3.setCallback(null,function(res) {
if(res.getState()=='SUCCESS') {
console.log('Call 3 : ', res.getReturnValue() );
// ... optionally more nestings here
}
});
$A.enqueueAction(call3);
}
});
$A.enqueueAction(call2);
}
});
$A.enqueueAction(call1);
},
If you press the button it executes in the console like this:
Call 1 : START.Apex1
Call 2 : START.Apex1.Apex2
Call 3 : START.Apex1.Apex2.Apex3
Can we use Promises for that scenario in order to improve readability and maintainability of that code?