这是现在的代码,承诺链与以前一样。我已经开始尝试使用Promise.all()来远离antiPattern
(function(){
'use strict';
function DOMObj(){
var that = this;
that.items = [];
that.getitems = function(url) {
return new Promise (resolve => {
$.getJSON(url, function (response) {
for (var i = 0; i < response.sales.length; i++) {
that.items.push(new ProductObj(response.sales[i], i));
}
resolve();
});
}
)
};
that.updateProductHTML = function(){
return new Promise(resolve => {
for( var i = 0; i < that.items.length; i++){
that.items[i].updateHTML();
}
resolve();
})
};
that.updateDOM = function() {
return new Promise(resolve => {
var thisHTML = '';
for( var i = 0; i < that.items.length; i++) {
if (i % 3 === 0 ) {
thisHTML += "<div class='row'>";
// console.log("START");
}
thisHTML += that.items[i].htmlView;
if ((i % 3 === 2) || i === (that.items.length - 1) ) {
thisHTML += "</div>";
console.log("FINISH");
}
}
$("#content").append(thisHTML);
resolve();
})
}
}
function ProductObj(product, i) {
var that = this;
that.photo = product.photo;
that.title = product.title;
that.subtitle = product.subTitle;
that.url = product.url;
that.htmlView = "";
that.index = i;
that.updateHTML = function() {
$.get('template.html', function(template){
that.htmlView = template.replace('{image}', that.photo)
.replace('{title}', that.title)
.replace('{subtitle}', that.subtitle)
.replace('{url}', that.url);
console.log(that.index + ' product has worked through html')
})
};
}
var myView = new DOMObj();
myView.getitems('data.json')
.then(
myView.updateProductHTML
)
.then(
myView.updateDOM()
)
.then(() =>{
$('.deleteButton').click(() => {
$(this).parent().remove();
});
//Promise.all([ myView.getitems('data.json'), myView.updateProductHTML, myView.updateDOM, () => {$('.deleteButton').click(() => {
//$(this).parent().remove();
//})}])
})();
到目前为止,代码按此顺序运行getItems => updateProductHTML
然后updateDOM
与它一起运行,我尝试添加的最后一个代码是按钮上的点击事件,需要最后运行
答案 0 :(得分:1)
将您的功能更改为返回将在回调函数完成时解析的承诺:
this.updateHTML = function() {
return new Promise(resolve => {
$.get('product-template.html', function(template) {
this.htmlView = template.replace('{image}', this.photo)
.replace('{string1}', this.string1)
.replace('{string2}', this.string2)
.replace('{url}', this.URL)
.replace('{class}', this.class);
resolve();
});
});
};
getData()
相同。
然后你应该能够轻松地链接步骤:
getData().then(updateHTML).then(updateDOM);