下面使用jQuery promises与回调结合使用的代码执行以下操作:
storeGroupOnServer()
将组UUID保存到服务器createGroupDomNode()
为该组创建一个DOM元素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: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);
}
答案 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;
});
}