Question

When communicating with a server in javascript in my single page browser application, I would like to provide a callback function that is always called after the server replies, regardless of whether the result was a success or some kind of error.

Two cases where I need this:

1) I want to disable a "save" button while waiting for the server's response, and enable it again after the server responds with an error or a success.

2) I have a polling mechanism where I want to prevent stacking of calls when the server for some reason is being slow to respond - I want to wait for one poll call to finish before making the next.

One solution I have right now involves making sure that two functions (success and error) get passed along as options in a long method chain, which feels like a fragile and cumbersome solution (pseudo-ish code):

  function doCall() {
    framework1.callit({success : myCallback, error : myCallback})
  };

  framework123.callit = function(options) {
    options = options || {};
    if (options.error) {
      var oldError = options.error;
      options.error = function(errorStuff) {
        // callit error stuff
        oldError(errorStuff);
      } else {
        // callit error stuff
      }
    generalCallFunction(options);
  }

  function generalCallFunction(options) {
    options = // ... checking success and error once again to get general success and error stuff in there, plus adding more options
    ajax( blah, blah, options);
  }

I also have a backbone solution where I listen to the sync event plus an error callback, in similar ways as above.

I'm always scared that error or success functions get lost on the way, and the whole thing is hard to follow.

Any framework or pattern for making this stuff as easy as possible? Is it a weird thing to have general things that should always happen whether the result was an error or a success?

Was it helpful?

Solution

You can use jQuery.ajax({ details here... ).always(callback);

Or, in Backbone

// logic to create model here
model.fetch().always(callback);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top