bart
bart

Reputation: 15298

How to turn nested jQuery Promises into flat code structure using .done() and .then()

Below's code using jQuery promises in combination with callbacks does the following:

  1. Saves Group UUID to server using storeGroupOnServer()
  2. Creates a DOM element for the group using createGroupDomNode()
  3. 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);
}

Upvotes: -1

Views: 63

Answers (1)

charlietfl
charlietfl

Reputation: 171669

Will give the start without having to rewrite the whole thing and let you fill in the rest

groupPromise.then(function(fileGroupInfo){
   return fileGroupInfo.uuid;
})
.then(storeGroupOnServer)
.then(createGroupDomNode)....



// uuid argument comes from return in groupPromise.then()
storeGroupOnServer = function(uuid) {
  // return the ajax promise
  return $.post('saveGroup.php', {uuid: uuid}, null, 'json')
        .then(function(data) {
           // return to next then() in chain which calls createGroupDomNode()
            return data.groupid;
        });
}   

Upvotes: 0

Related Questions