如何使用.done()和.then()将嵌套的jQuery Promises转换为平面代码结构

时间:2018-11-16 20:17:52

标签: jquery promise es6-promise uploadcare

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

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

如何使用.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: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);
}

步骤3:createNewChildDomNode():

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

1 个答案:

答案 0 :(得分: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;
        });
}