AJAX the Good (Asynchronous) Way
✶: 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 :
- Never do synchronous request → because this will block main thread
- 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 :
- Create or have an object (state object) that will store all requests states (done/failed/in progress) + may be result
- 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.
The ‘this’ keyword in callback function
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 !