2

Is there a way in lightning to keep track of enqueued server side actions and cancel them if some event happens on the client before the action completes?

2
+50

The short answer is no. Once you send an action to the server it's going to complete executing whether or not the component on the client side is still valid. (Source)

In terms of alternatives, it depends on exactly what the specific scenario you're working with is. I have a few guesses for you, but if I miss it, let me know.

  1. User makes a change to record, your code sends the record to the server. User makes another quick change to the record and you want to cancel the save in progress and send a new save.
    • In this case, it makes sense to debounce the save call all together. (Wait until the user has stopped interacting for x milliseconds before making the server call.) If you use lodash or similar library the code is straight forward.

controller:

doSave: function(cmp, evt, helper){
    if(!helper.debouncedSave){
        helper.debouncedSave = _.debounce(helper.doSave, 800); //you can play with this number to see what is best
    }
    helper.debouncedSave(...);
}

helper

doSave : function(........){
    $A.getCallback( ...savelogic)();
}
  1. Your server response contains information that could be outdated by the time the response arrives based on client interactions.

    • This one is more tricky. You'll like have to keep track on the client of what is sent the server and handle the responses smartly.
  2. You have long running code you want cancelled if the user the navigates away.

    • Check out the abortable/background action docs
  3. You need Undo/Redo type abilities

    • You'll have to keep track on the client of which actions you've dispatched to the server, and if an undo is necessary, dispatch the opposite action when the original server action returns.
  4. If you absolutely have to have it.

    • So I wouldn't recommend this, but if you absolutely cannot adjust the client-side architecture to alleviate your problem, there are few hacky ways to put something like this in place. I could expand on the specifics if asked, but it would involve essentially debouncing the calls on the server by relying on the database as a temporary storage or leveraging the queue/batch apis. Either way you're going to run into limit nightmares and just overall bad news.

If you can provide more specifics, I can be more targeted on workarounds.

  • 1
    Great answer and thanks! I think debouncing will work for my scenario. Have to wait 12 hours to award the bounty but it's yours – Scott Morrison Jun 20 '17 at 2:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.