问题描述
我正在使用两个Ajax Get请求,每个请求都有一个if条件,以防万一不适用,我必须保存原因并将其显示在一个警告消息中。但是我正在显示两个警报,每个警报针对一个获取请求。这是我的代码:
var errorMessage = "";
$.get(url,function (responseGET) {
var responseGETHtml = $(responseGET).find(".data-table tbody").html();
console.log("responseGETHtml",responseGETHtml,typeof responseGETHtml);
var rowCount = $(responseGETHtml).filter("tr").length;
if (rowCount > 1) {
errorMessage +=
"There is more than one result for invoice #" + invoiceId + "\n";
}
});
var url2 = "/einnahmen/" + customerId;
url = url2.trim();
$.get(url2,function (responseGET) {
var responseGETHtml2 = $(responseGET).find(".data-item-form form.form");
if (brutto < csvBrutto) {
errorMessage += "Brutto of csv is bigger than Brutto in table" + "\n";
}
if (errorMessage != "") {
alert(errorMessage);
} else {
responseGETHtml
.find(".form-choice .forminput-zahlungsweise")
.prop("checked",true)
.val("Überweisung");
$.post({
url: "/einnahmen/?filter[rechnung_nr]=" + invoiceId,data: responseGETHtml.serialize(),success: function (responsePOST) {
alert($(responsePOST).find(".message").text());
},dataType: "html"
});
}
});
我如何只显示一条包含所有错误的警报消息?
解决方法
我的想法是使用Promises,尤其是Promise.all()。
- 让我们将每个请求转换为一个承诺,该承诺将以
errorMessage
作为参数来解决请求的结果。 - 在这些承诺上使用Promise.all(),当两个请求都解决后,新的承诺将得到解决
- 如果一个或多个请求给出了错误,如果没有恢复您的代码,请加入错误消息
const request1 = new Promise(resolve => {
$.get(url,function(responseGET) {
var responseGETHtml = $(responseGET).find(".data-table tbody").html();
console.log("responseGETHtml",responseGETHtml,typeof responseGETHtml);
var rowCount = $(responseGETHtml).filter("tr").length;
const errorMessage = rowCount > 1 ? `There is more than one result for invoice #${invoiceId}` : '';
resolve(errorMessage);
});
});
var url2 = "/einnahmen/" + customerId;
url = url2.trim();
const request2 = new Promise(resolve => {
$.get(url2,function(responseGET) {
var responseGETHtml2 = $(responseGET).find(".data-item-form form.form");
const errorMessage = brutto < csvBrutto ? 'Brutto of csv is bigger than Brutto in table' : '';
resolve(errorMessage);
});
});
Promise.all([request1,request2]).then(errorMessages => {
// this code is executed when both request has resolved
// has at least one request resolved with an error message ?
const hasError = errorMessages.some(error => error != '');
if (hasError) {
alert(errorMessages.join('\n'));
} else {
// this code is executed when both request has resolved with no error.
responseGETHtml
.find(".form-choice .forminput-zahlungsweise")
.prop("checked",true)
.val("Überweisung");
$.post({
url: "/einnahmen/?filter[rechnung_nr]=" + invoiceId,data: responseGETHtml.serialize(),success: function(responsePOST) {
alert($(responsePOST).find(".message").text());
},dataType: "html"
});
}
});