Queuing Ajax Requests in JS Web Apps

Queueing Ajax requests in JavaScript Web Apps can be important, especially if the interface doesn’t always represent database state.

In both Backbone and Spine, the default behavior is to update the user-interface before sending requests to the server, i.e. an asynchronous user-interface. However, this can cause race conditions. For example:

  1. User creates a record, say a page
  2. Interface is updated and an POST request is sent
  3. User immediately deletes page
  4. DELETE request is sent to the server
  5. The server responds to the DELETE request before the POST request to create the page has finished.
  6. Server 404s because it can’t find the referenced page by ID

The solution to this race condition is to queue Ajax requests, particularly destructive ones (POST, PUT, DELETE). I’ve written a very simple jQuery 1.9 plugin to do just this. All you need to do is pass a queue flag when creating Ajax requests.

jQuery.ajax({type: 'POST', queue: true});

You can also set queue to a named queue string, effectively name-spacing specific queues.

We still have a problem if a particular request fails, as the interface will now be out of sync with the database. I usually recommend treating this as an exceptional circumstance, and prompt the user to reload the page. Incidentally, this is exactly how Facebook and Twitter solve the problem.


This article is in the Monocle series.

 
665
Kudos
 
665
Kudos

Read this next

A browser API for one click payments

TLDR: A JavaScript API to access the browser’s autocomplete data, allowing one-click signups and purchases. In the early 1900s, when stagecoaches were first being converted into automobiles, the engineers were so entrenched by... Continue →