The statement $A.enqueueAction(action); makes an asynchronous network request and result is processed via a callback. In your code, you are not waiting for callback to complete before trying to access the result.
Here are steps you can follow to get the list of accounts in your lightning component.
Write an Apex controller and add an @AuraEnabled method which returns list accounts.
// snippet
public class MyAccountListController {
@AuraEnabled
public static List<Account> getAccounts() {
return [Select Id, Name From Account limit 100];
}
}
Create a Lightning component and bind the Apex controller to component.
// snippet
<aura:component controller="MyAccountListController">
</aura:component>
In your component, declare an attribute to hold Account records as follows.
<!-- list of accounts -->
<aura:attribute name="accounts" type="Account[]" />
Add a javascript function in Client-side controller for lightning component to get the list of accounts and assign it to attribute in lightning component.
getAccountList: function(component,event,helper) {
var action = component.get('c.getAccounts');
// Set up the callback
var self = this;
action.setCallback(this, function(actionResult) {
var state = actionResult.getState();
if(state == 'SUCCESS') {
component.set("v.accounts", actionResult.getReturnValue());
console.log(component.get("v.accounts"));
} else if(state == 'ERROR') {
console.error(actionResult.getError());
} else {
console.log("something went wrong!");
}
});
$A.enqueueAction(action);
}
Call the getAccountList javascript function from lightning component. It's upto you how want to invoke that function. Just for completion, I'm going bind to this function to init event of lightning component. It will load account list when component loads.
<aura:handler name="init" action="{!c.getAccountList}" value="{!this}" />
Hope this helps.
$A.enqueueAction(action)adds the server-side action as queue of actions to be executed asynchronous and have callbacks.you put an alert after$A.enqueueAction(action)it is called first thats y you getting empty.you check it in successcallback