I'm currently building a simple lightbox for my website using jquery.deferred patterns and while doing so I'm trying to maintain a flat chain of asynchronous operations and avoid the infamous nested callback pyramid of doom. Here is what I have so far:
$('#gallery a').click( function() {
var id = $(this).attr('id'); // Id of the current selection
var current = 0; // Array index of the current item
getTpl() // Get and load lightbox template
.then(getData) // Get JSON data of the selected item
.then(getItem) // Pass JSON data and get the item
.then(loadItem) // Use JSON data to create the HTML output
.done(function() {
// Wrap everything up, intialize the lightbox controls
// (requires the JSON data) and load the lightbox
});
});
The first two steps (getTpl, getData) are simple AJAX promises and work fine. I can also pass the JSON data further down the chain to the third step (getItem). That's where the problems start:
- I have to pass the variables 'id' and 'current' from the higher scope to the functions that are called during the chain (getItem and loadItem use these variables to construct URLs and create HTML output). How do I do that without breaking the asynchronous chain?
- Do I really have to return my JSON data (and other variables) from every function along the way to use it further down the chain? Isn't there an easier way to keep the data and necessary variables available throughout the entire chain?
- Can I throw random operations into the chain, e.g. a simple jquery fadeIn? That's what '.done' is for, because '.then' expects a new promise, right?
Thanks in advance!