A little context
Here’s the situation. On the page we have checkboxes for selecting rows of data, and a button that performs an action on the selected rows. The action happens via an ajax POST back to the server. The POST requires a certain piece of data from each row be sent in the request, but on this particular page, not every row will have that data until a different action creates it. Some rows will, some won’t. So, to make sure every row that is being submitted for the POST has all the data required, we have to fire an action for those rows that don’t have it, get the response, put the data from that first request into place where the section action needs it to be, then, and only then, fire the second response.
Promises can make this kind of chaining possible without the use of callbacks.
The POST action is wrapped in a “when”. The “when” executes that POST only when its params return back a fulfilled promise., and it just waits until then or errors if the promises come back rejected. The first promise is collecting the data from the rows that already have the data. The second promise builds an array of the checked rows that don’t have the data, then uses the $.apply to apply each promise in that array of promises to a different “when” function. When all those promises resolve (each GET request in the array returns back successful), that “when” returns a resolved promise to the other “when” function, which then (if the other param has resolved) executes the POST with all the appropriate data.
I’ve read about and studied promises for some time but this was the first application of that knowledge and it worked out perfectly. I’m looking forward to the next time I can put promises into action.
Here’s the code:
Latest posts by Jesse Michelsen (see all)
- IdPinThat.com 2.0 Release: This Changes Everything 😉 - August 1, 2016
- IdPinThat.com: From Idea To Launch In Ten Days - January 28, 2014