I'm working on a JavaScript application that has to perform two separate checks via AJAX. Depending on the result of each check, behavior differs. The case I'm interested in here is when both checks are successful. I've identified a few ways to do this, and I want to get some feedback from SO about what they think the best approach is.
- Synchronous AJAX calls: This is what I inherited, and it's gone. It causes browser and system lockups, though it does allow you to keep the processing of responses in a single thread of execution.
- Daisy-chaining: Make an AJAX call to perform the first check, and if it passes, do the second check in the first check's callback. Process the second check, and if it passes, we're successful. This is the most straightforward solution, but it sees to unnecessarily couple my two checks. I also feel like serializing my checks is unnecessary and degrades performance.
- Custom Events: Using YUI's Event module and Custom Event utility, fire off both AJAX calls simultaneously. Create a custom event for each success case, and have the callbacks that process the AJAX responses throw the appropriate event for each check on success. The handler for each event can then subscribe to the other event, and if it is thrown then we've successfully completed.
My question relates to the third approach, which is the one I favor. I like the fact that my handlers are connected only through the events being thrown, and that the AJAX calls can happen simultaneously. What I want to know is, has anyone else used this module in this way? What sort of pitfalls can I expect? I worry that I might have set myself up for a race condition--how can I alleviate this? And finally, to anyone who's read this far, is there a better way? Is my list non-exhaustive, or is the design fundamentally flawed? Constructive criticism and comments are more than welcome.
Edit: While the server requests do use sessions, they are unrelated to each other and don't write session data, so there's no reason for them not to happen in parallel on the server (unless PHP sessions have some limitation I don't know about). We do server-side checks as well, but we find that before certain important events we need to check with the server immediately before so that we can inform the user in the rare event that something changes.