AJAX the Good (Asynchronous) Way

TL;DR : Javascript and AJAX are asynchronous, so your code must be asynchronous✶ too !

✶: JS is event driven, which is some kind of asynchronous, and AJAX is asynchronous

Be carefoul : Never, never use synchronous AJAX request !!!
It will make your apps feels laggy, and on bad network it can be unusable : because 1 long request block the main loop and all processing is blocked too.

2 Things to remember

When doing xhr request you have to remember 2 things :

  1. Never do synchronous request → because this will block main thread
  2. Give all info to your callback function (the callback function may want to re-do a request or do other process on some errors) → the best way is to return the whole xhr object as first param of your callback, this object contains all info about errors/success or request called if callback want to retry.

So, it’s just that ? Yes, but that means that your code should manage request that don’t succeed, or succeed not in the attended order etc. → This can be tricky sometimes but it’s the only way to go.

How to synchronize multiple asynchronous requests

My method is :

  1. Create or have an object (state object) that will store all requests states (done/failed/in progress) + may be result
  2. Start each request the same times, then all callbacks can use the state object to start other request or manage errors

… this is not the only way, you can do as you want, but important is : don’t forget to manage errors/timeout in your callback.

NOTE: if you are ES6 ready you should use promise
NOTE2: If you are using plenty of async and can’t use ES6 promise you may look at async.js

The ‘this’ keyword in callback function

If you want to use ‘this’ in a callback you should look at : call() and apply() which allow you to define the this context in the callback function. bind() maybe interesting too.

Further reading : Todd motto, an in depth explanation of the ‘this’ keyword in JS.

NOTE: If you use a singleton object you can refer to it, this can be an easy way to avoid some ‘this’ context problem

A word about XML

Don’t use XML !

Javascript has JSON : parsing and generation is INSIDE javascript : so it’s really simple to just use it, don’t use xml or whatever. Do not even think about it !

Maybe one day you will want to use another format for performance reason (like protobuf, capnproto or flatbuffer), but I hardly see a point for xml.