function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Gaurav Sinha 27Gaurav Sinha 27 

call other action on completion of previous action in Lightning

Hi All Veterans
I have written a component where I have to call other action on completion of the first action. Can anyone help me in this please as this is an urgent requirement. Below is the function:
SearchHelper: function(component, event,helper) {
		alert("search helper fired");
     	var country = component.find('country').get("v.value");
        var city = component.find('city').get("v.value");
        var street = component.find('street').get("v.value");
        var state = component.find('stateProvince').get("v.value");
        var postal = component.find('postalCode').get("v.value");
        var action = component.get("c.EMDMaddressDocLightning");
        action.setParams({
            'country':country,
            'city':city,
            'street' : street,
            'state' : state,
            'postalcode' : postal
        });
        action.setCallback(this, function(response){ 
            var state = response.getState();
            if (state === "SUCCESS") {
               var storeresponse= response.getReturnValue();
                alert("StoreResponse==>"+storeresponse);
                if (storeresponse.length==0){
                    component.set("v.NoResults", true);
                }
                if (storeresponse.length > 1){
                    component.set("v.ResultsFound", true);
                    component.set('v.AddDocColumns', [
                        {label: 'Street', type: 'text', value:'street'},
                        {label: 'City', type: 'text', value:'city'},
                        {label: 'State', type: 'text', value:'state'},
                        {label: 'Country', type: 'text', value:'country'},
                        {label: 'Postal Code', type: 'text', value:'postal'},
                    ]);
                    
                }
                if (storeresponse.length == 1){
                    storeResponse.forEach(function(record){ 
                        component.set("v.country", record.country);
                        component.set("v.city", record.city);
                        component.set("v.street", record.street);
                        component.set("v.stateProvince", record.state);
                        component.set("v.Postalcode", record.postalcode);
                });
                }
                component.set("v.AddressResult",storeresponse);
            }else if (state === "INCOMPLETE") {
                alert('Response is Incompleted');
                component.set("v.NoResults", true);
           }else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        alert("Error message: " + 
                                    errors[0].message);
                    }
                }
                component.set("v.NoResults", true);
            }else {
                    alert("Unknown error");
                component.set("v.NoResults", true);
                }
        });
     //2nd action starts here...

     component.set('v.mycolumns', [
             {label: 'Name', fieldName: 'Name', type: 'url', sortable: true,
             typeAttributes: {label: { fieldName: 'Name' }, target: '#target'}},
             {label: 'NON-LATIN NAME', fieldName: 'Non_LatinName__c', type: 'text', sortable: true},
             {label: 'ADDRESS', fieldName: 'Address__c', type: 'text', sortable: true},
             {label: 'City', fieldName: 'City__c', type: 'text', sortable: true},
             {label: 'City Region', fieldName: 'CityRegion__c', type: 'text', sortable: true},
             {label: 'State', fieldName: 'State__c', type: 'text', sortable: true},
             {label: 'Country', fieldName: 'Country__c', type: 'text', sortable: true},
             {label: 'MDCP Id', fieldName: 'MDCP_Id__c', type: 'text', sortable: true},
             {label: 'DUNS', fieldName: 'DUNS__c', type: 'text', sortable: true},
             {label: 'Domestic DUNS', fieldName: 'Domestic_DUNS__c', type: 'text', sortable: true},
             {label: 'Global DUNS', fieldName: 'Global_DUNS__c', type: 'text', sortable: true},
             {label: 'Tax ID', fieldName: 'Tax_ID__c', type: 'text', sortable: true},
             {label: 'Is Competitor', fieldName: 'Is_Competitor__c',type:'boolean', 
              "cellAttributes": {"iconName": { "fieldName": "IsCompetitor" },sortable: true}},
             {label: 'Out Of Business', fieldName: 'isOutOfBusiness__c',type:'boolean',
             "cellAttributes": {"iconName": { "fieldName": "OutOfBusiness" }, sortable: true}},
         ]);
        // show spinner message
         component.find("Id_spinner").set("v.class" , 'slds-show');
        var action2 = component.get("c.GetAccounts");
        //var label= Label.DEAL_Query_Limit;
        var pageSize = component.get("v.pageSize");
        var pageNumber = component.get("v.pageNumber");
        var MDMquery='';
        var method='';
       	var city= component.find('city').get("v.value");
             if(city){
                 if(city.Length < 3){
                 alert("city: Please provide atleast 3 characters");
                 }             
             }
        var name= component.find('name').get("v.value");        
        var country= component.find('country').get("v.value");        
        var duns= component.find('duns').get("v.value");
        //var mdcpid= component.find('MDCPID').get("v.value");        
        var stateProvince= component.find('stateProvince').get("v.value");
        var postalCode= component.find('postalCode').get("v.value");
        var taxiD= component.find('taxiD').get("v.value");
    	var street= component.find('street').get("v.value");
        //var iscompetitor= component.find('IsCompetitor').get("v.value");      
        if(name || taxiD || city || stateProvince || country || postalcode)
        {            
            if(name)    MDMquery=MDMquery+'q=(+ organizationExtendedName:('+name+') OR organizationNonLatinExtendedName:('+name+') OR organizationReportingName:('+name+') OR organizationLegalName:('+name+') OR tradeStyleNames:('+name+'))';
            if(taxiD)   MDMquery=MDMquery+' AND taxIds:(+'+taxiD +')';
            if(city)    MDMquery=MDMquery+' AND (+ latinCity:('+city+') OR cityRegion:(+'+city+'))';
            if(stateProvince)   MDMquery=MDMquery+' AND state:(+'+stateProvince+')'; 
            if(country)
                 {            
                    if(country.includes(" ")){
                           MDMquery=MDMquery+' AND countryName:(+"'+country+'")';  
                    }else{
                           MDMquery=MDMquery+' AND countryName:(+'+country+')';  
                    }
                }        
            if(postalCode) MDMquery=MDMquery+' AND postalCode:(+'+postalCode+')';            
            MDMquery=MDMquery+' LIMIT '+ '200' +' OFFSET '+ pageSize*pageNumber + '';
                //' AND isOutOfBusiness:(+ false)'+      
            MDMquery=MDMquery.replace('&',' ');
            method='MDMSearch';
             }else if(duns)
             {
             	method='getDetailbyDuns';
             }else if(mdcpid)
             {
             	method='getDetailbyOrgId';
             }
    if(country || street || city || stateProvince || postalcode){
    	component.set("v.AddressDoc",true);
    }
        action2.setParams({
            'Query':MDMquery,
            'SearchMethod':method,
            'pageSize' : pageSize,
            'pageNumber' : pageNumber
        });
        action2.setCallback(this, function(response) {            
           // hide spinner when response coming from server 
            component.find("Id_spinner").set("v.class" , 'slds-hide');                    
            var state = response.getState();
            if (state === "SUCCESS") {                
             var pageSize = component.get("v.pageSize");
                // hold all the records into an attribute named "AccountData"
                component.set('v.AccountData', response.getReturnValue());
                // get size of all the records and then hold into an attribute "TotalNumberOfRecord"
                component.set("v.TotalNumberOfRecord", component.get("v.AccountData").length);
                // set star as 0
                component.set("v.startPage",0);
                
                component.set("v.endPage",pageSize-1);
                var PaginationList = [];
                for(var i=0; i< pageSize; i++){
                    if(component.get("v.AccountData").length> i)
                        PaginationList.push(response.getReturnValue()[i]);    
                }
                component.set('v.searchResult', PaginationList);
                component.set('v.isSending',false);
				component.find("accordion").set('v.activeSectionName', 'Search Results');
             var storeResponse = response.getReturnValue();
             storeResponse.forEach(function(record){ 
                    if(typeof record.Id === true || typeof record.Id === false){                         
                        // https://www.lightningdesignsystem.com/icons/#utility 
                        if(record.Is_Competitor__c=== true){
                            record.IsCompetitor = 'utility:check';
                        }
             			else if(record.isOutOfBusiness__c=== true){
                            record.OutOfBusiness = 'utility:check';
                        }                       
                    }
                });
             //alert('storeResponse'+JSON.stringify(storeResponse));
                // if result size is 0 ,display no record found message on screen.
                if (storeResponse.length == 0) {
                    component.set("v.Message", true);
                }else if (storeResponse.length >= 200) {
                    component.set("v.Notification", true);
                } else {
                    component.set("v.Message", false);
                    component.set("v.Notification", false);
                }                
                // set numberOfRecord attribute value with length of return value from server

                helper.sortData(component, component.get("v.sortedBy"), component.get("v.sortedDirection"));
				//var refreshview = $A.get('e.force:refreshView').fire();                
            }else if (state === "INCOMPLETE") {
                alert('Response is Incompleted');
            }else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        alert("Error message: " + 
                                    errors[0].message);
                    }
                } else {
                    alert("Unknown error");
                }
            }

        });        
        $A.enqueueAction(action);
        $A.enqueueAction(action2);
    },

 
Gaurav Sinha 27Gaurav Sinha 27
I Have to call both the actions on same button click
Khan AnasKhan Anas (Salesforce Developers) 
Hi Gaurav,

Greetings to you!

Order of action execution is not guaranteed on the server. The platform has no way of knowing if one method will take longer than the other, and there's no benefit to reordering because all of the responses will arrive in a single package anyways.

You can write a second controller inside the First setCallBack method, the third controller inside the second Controller and so on. Please refer to the below links which might help you further with the above requirement.

https://developer.salesforce.com/forums/?id=906F0000000kKDRIA2

https://salesforce.stackexchange.com/questions/171073/lightning-multiple-enqueued-actions-execute-action-when-all-are-done/171078

https://salesforce.stackexchange.com/questions/161566/order-of-server-action-callbacks-invoked-in-lightning/161972#161972

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas 
Gaurav Sinha 27Gaurav Sinha 27
Hi Anas Thanks for the response, I tried that but its not getting saved, may be there is some compile error which I am not able to find,It would be great help if you could guide me with ordering the actions with the complete code. Thanks and Regards Gaurav Sinha
Naveen KNNaveen KN
Try calling the second method once you get a response from the server in the first action. 

Pseudo code:

action1 code goes here
     if( state = success){
    $A.enqueueAction(action2);
}

action2 code goes here

let me know if that works. 

Regards,
Naveen
 
Gaurav Sinha 27Gaurav Sinha 27
Hi Naveen

Thanks for the response, where we are enquing first action in this pseudo code? and is it possible to enque to action before writing the code for that action as your pseudo code shows the same.

Regards
Gaurav Sinha
Naveen KNNaveen KN
Hi Gaurav, 
the first action enqueue is at the same place. no changes required. 

action1 code goes here
     if( state = success){
    $A.enqueueAction(action2);
}

action2 code goes here
$A.enqueueAction(action);

for your second question, I think that should work if I am not wrong. please try and let me know if you see any issues.

Regards,
Naveen K N