Below's code using jQuery promises in combination with callbacks does the following:
- Saves Group UUID to server using
storeGroupOnServer()
- Creates a DOM element for the group using
createGroupDomNode()
- Creates child elements for each image, using
createNewChildDomNode()
How can this be written more flat (avoiding the nesting), using .then()
?
groupPromise.done(function(fileGroupInfo) {
storeGroupOnServer(fileGroupInfo.uuid, function(groupid){
createGroupDomNode(groupid, function(groupnode){
$.each(arrayOfFiles, function(i, file) {
file.done(function(fileInfo) {
createNewChildDomNode(fileInfo.cdnUrl, groupnode);
});
});
});
});
});
Step 1: storeGroupOnServer():
storeGroupOnServer = function(uuid, callback) {
$.post('saveGroup.php', {uuid:uuid},
function(data) {
callback(data.groupid);
},'json');
};
Step 2: createGroupDomNode():
createGroupDomNode = function(groupid, callback) {
var cloner = $('#cloner');
var newnode = cloner.clone(true);
newnode.attr('id',groupid);
newnode.removeClass('hide');
cloner.after(newnode);
callback(newnode);
}
Step 3: createNewChildDomNode():
function createNewChildDomNode(imgpath, groupdom){
imgnode = $('<img/>').attr('src',imgpath);
picnode = $('<picture/>').append(imgnode);
$(groupdom).first().prepend(picnode);
}
Will give the start without having to rewrite the whole thing and let you fill in the rest