4

In lightning or VF page, there is usually more than one set of data need to be initialized. Say if we have two list of SObjects of different type need to get queried/initialized from database, what should we do in this case. I am currently using multiple enqueued actions to achieve this, as in the below code:

    var action = component.get("c.getCurMessage");

        action.setCallback(this, function(response) {
            //...
        });

        $A.enqueueAction(action);
    }

    var action2 = component.get("c.getHelperList");

    action2.setCallback(this, function(response) {
        //...
    });

    $A.enqueueAction(action2);

This can resolve the issue. But the disadvantage about this method is obvious - it needs multiple server calls to retrieve the data. I have thinked about using a JSON string to carry all the data to front-end side and analyze the string in front-end but it will obviously make code very complex. Is there a better way of doing this?

2 Answers 2

5

It doesn't matter. When multiple requests are posted in close proximity to each other, they'll all be processed in the same round-trip. There's a blog post about how this works. Also read about the Queueing of Server-Side Actions.

Generally speaking, this means it's more efficient to enqueue multiple actions than once, rather than trying to bundle them together as a single function call, or trying to chain them together.

2
  • Um... Interesting. I do see my second component rendering a little bit slower than the first one which are in two different actions. But the difference is small though. Thank you for the information.
    – Lance Shi
    Nov 4, 2016 at 6:59
  • @LanceShi Chaining actions should require more time than just trusting the batch, although client rendering might affect that.
    – sfdcfox
    Nov 4, 2016 at 7:03
0

A possible solution that I am using is to create an apex class that contains all the data that I need in my lightning component, and return it to the client side component.

This way I can use it easily in the component markup.

So in your example - I would create an apex class that contains 2 members declared as AuraEnabled variables:

@AuraEnabled
public String message{get; set;}

@AuraEnabled
public List<String> helpers {get; set;}

Then in the server side controller, I would create this class as an instance and load it, then return it to the component client side and it will be available there.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .