Promise.all处理多个异步请求
自己测试用例:
需求描述:需要多次请求后台查询选中的多个模型的构件,然后将获取的所有的构件信息进行分组显示。
let pArr = [];
for (var i = 0; i < selectedObjecGroup.length; i++) {
var LayerElement = selectedObjecGroup[i];
var ElementIds = LayerElement[0].value;
var WebFileID = LayerElement[0].key;
pArr.push($.ajax({
type: "POST",
url: "/DesignManage/ModelView/GetElementsPropertyList?rdo=" + Math.random(), //ajax请求地址
data: {
WebFileID: WebFileID,
ElementIds: JSON.stringify(ElementIds)
},
success: function (data) {
},
error: function (msg) {
layWin.showMsg(msg, 5);
}, complete: function (data) {
}
}));
}
Promise.all(pArr).then((result) => {
let data = [];
result.map(function (item) {
item.map(function (itemData) {
data.push(itemData)
})
})
if (data.length > 0) {
$.each(data, function (i, o) {
var BOQ = {};
$.each(o.properties[0].items, function (index, obj) {
if (obj.key == "categoryName") {
BOQ.categoryName = obj.value;
}
if (obj.key == "family") {
BOQ.family = obj.value;
}
if (obj.key == "familyType") {
BOQ.familyType = obj.value;
}
});
BOQ.volume = 0;
if (typeof (o.properties[1]) != "undefined") {
$.each(o.properties[1].items, function (index, obj) {
if (obj.key == "体积") {
BOQ.volume = parseFloat(obj.value);
}
});
}
BOQList.push(BOQ);
});
var BOQgroup = groupBy(BOQList, function (item) {
return [item.categoryName];
});
$.each(BOQgroup, function (index, obj) {
var BOQDiv = {};
BOQDiv.Id = index + 1;
BOQDiv.categoryName = obj[0].categoryName;
BOQDiv.Num = obj.length;
BOQDiv.volume = 0;
$.each(obj, function (childrenindex, childrenobj) {
if (typeof (childrenobj.volume) != "undefined")
BOQDiv.volume += childrenobj.volume;
});
BOQListDiv.push(BOQDiv);
});
$.each(BOQListDiv, function (index, obj) {
var html = "";
html += '<tr class="bf-group-content">';
html += '<td class="bf-key tab_BOQ" style="width:45px;">' + obj.Id + '</td>';
html += ' <td class="bf-key tab_BOQ" style="width:100px;">' + obj.categoryName + '</td>';
html += ' <td class="bf-key tab_BOQ" style="width:65px;">' + obj.Num + '</td>';
html += ' <td class="bf-key tab_BOQ" style="width:80px;">' + obj.volume.toFixed(3) + '</td>';
html += '</tr > ';
$("#BOQDiv_Body").append(html);
$("#BOQMsg").hide();
});
}
else {
$("#BOQMsg").show();
$("#BOQMsg").text("暂无数据");
}
}).catch((error) => {
$("#BOQMsg").show();
$("#BOQMsg").text(error);
})