5

I am using javascript remoting. I have a situation where I need remote actions to execute in order.

The problem I am running into is the second remote action executes prior to the first one finishing. Since remote actions are asynchronous, is it possible to execute them in order? What is the best way to do so?

Visualforce.remoting.Manager.invokeAction(
  '{!$RemoteAction.ChoptankRates.method1}',
  document.getElementById('var1').value,

  function(result, event) {
    document.getElementById('var1').value = result[0].somevalue;

    //SECOND REMOTE ACTION SHOULD EXECUTE NOW.
  }
);
Visualforce.remoting.Manager.invokeAction(
  '{!$RemoteAction.ChoptankRates.method2}',
  document.getElementById('var1').value,

  function(result, event) {
    //do something here
  }
);

2 Answers 2

6

Put the second invocation inside the callback of the first invocation. It's as simple as moving the second block of code directly into the function where you typed "second function call should happen now."

If you wanted to do this using an actual pattern, take a look at promises, such as when-then.

1
  • Turns out it was much simpler than this. A response from a callout contained a null value. The second remote action executed and referenced the null value giving the illusion that the second method was executing prior to the first!
    – Berg
    Commented Apr 2, 2015 at 14:40
1

Another way to do this would be to use Kris Koval's Q library, or another promise library. Write your code such that each promise returns yet another promise that can be therefore chained. Promises will then defer solution in the order they're chained. Much less mess than callbacks as well.

You must log in to answer this question.

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