[SalesForce] How to repeatedly poll a server-side controller for an action in a Lightning Component

There's a Lightning Component with a button. Its onClick attribute points to a client-side controller's function. It invokes helper's function which I would like to start a polling routine to a server-side controller.

Client's code:

initiatePolling : function(cmp, callEvent) {
        var myFunction = function() {
            console.log('Inside myFunction');
            var action = cmp.get("c.myServerSideFunction");
            action.setCallback(this, function(response) {
                console.log("Inside myServerSideFunction callback");
                if (response.getState() === "SUCCESS") {
                    console.log("Success: " + response.getReturnValue());
                } else {
                    console.log("Error");
                }
            });
            $A.enqueueAction(action);
            setTimeout(myFunction, 1000);
        }
        myFunction();
}

Server's code:

@AuraEnabled
public static String myServerSideFunction() {
    return 'Server-side callback';
}

The problem is that after clicking the button, in a console I receive the following messages:

Inside myFunction
Inside myServerSideFunction callback
Success: Server-side callback
Inside myFunction
Inside myFunction
Inside myFunction
etc...

It looks like the server-side callback is received only once. Why does it happen? How can I make it work?

Best Answer

Since the actions are asynchronous, they will not execute in the order you expect. Your code works, you just need to you leave your console open long enough and you will see batches of server side actions executed simoultaneously after some time. This is specified in the lightning components developer guide section under Calling a Server-Side Actions

$A.enqueueAction(action) adds the server-side controller action to the queue of actions to be executed. All actions that are enqueued will run at the end of the event loop. Rather than sending a separate request for each individual action, the framework processes the event chain and batches the actions in the queue into one request. The actions are asynchronous and have callbacks.

This post answered by @martin --> Use of setCallBack() in Lightning can provide furhter details on using callback functions in lightning controllers and interacting with servers side actions

Related Topic