-1

下面的代码结合使用 jQuery Promise 和回调执行以下操作:

  1. 将组 UUID 保存到服务器使用storeGroupOnServer()
  2. 使用为组创建 DOM 元素createGroupDomNode()
  3. 为每个图像创建子元素,使用createNewChildDomNode()

怎样才能写得更扁平(避免嵌套),使用.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);
                });
            });
        });
    });
});

第 1 步:storeGroupOnServer():

storeGroupOnServer = function(uuid, callback) {
    $.post('saveGroup.php', {uuid:uuid},
    function(data) {
        callback(data.groupid);
    },'json');
};

第 2 步:创建GroupDomNode():

createGroupDomNode = function(groupid, callback) {
    var cloner = $('#cloner');
    var newnode = cloner.clone(true);
    newnode.attr('id',groupid);
    newnode.removeClass('hide');
    cloner.after(newnode);
    callback(newnode);
}

第 3 步:createNewChildDomNode():

function createNewChildDomNode(imgpath, groupdom){
    imgnode = $('<img/>').attr('src',imgpath);
    picnode = $('<picture/>').append(imgnode);
    $(groupdom).first().prepend(picnode);
}
4

1 回答 1

0

无需重写整个内容即可开始,其余部分由您填写

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;
        });
}   
于 2018-11-16T20:54:22.127 回答