jQuery Transactions using Promises

I’ve had a couple projects recently where I needed to perform an action pending the successful completion of a variable number of AJAX requests. In the past, I have used a global counter to keep track of the number of successful requests, in the fashion of:

This sort of works, but running the counter check each time has always felt wrong as my AJAX requests are just concerned with GET/POST’ing data and shouldn’t be performing this unrelated task. The more serious problem is when one step fails, we have to back up to find which call failed and that requires an attempt to call a success/error function on each iteration and in both the success and error callbacks of the AJAX requests. On top of this, I have been reading about Promises and wanted to try them out. So, here is a documented rewrite using promises.

Leave a Reply