Tôi gặp sự cố khi tải thuộc tính errorCount
để tăng trong quá trình thực thi mã. Vấn đề tôi đang gặp xảy ra bên trong yêu cầu $.ajax
, cụ thể hơn là phương thức addError()
.Bộ đếm đối tượng Javascript không tăng như mong đợi
Nếu tôi sử dụng mã sau bên dưới để kiểm tra số lượng hiện tại errorCount
, nó luôn trả về 0
mặc dù tôi đã tạo lỗi theo cách thủ công. Nhưng bên trong của phương pháp ajax sau khi tôi gọi addError()
và sau đó kiểm tra giá trị của errorCount
nó cho thấy 1
như nó cần. Tôi đã làm gì sai?
var boom = new test(settings, formData, search);
console.log(boom.errorCount);
boom.queueCalls(settings);
console.log(boom);
console.log(boom.errorCount);
Đây là mã đối tượng:
function test(a, b, c) {
this.settings = a;
this.formData = b;
this.search = c;
this.errorCount = 0;
}
test.prototype = {
constructor: test,
queueEmails:function(settings, formData, search) {
var url = '/example-url-endpoint';
var data = {postData: settings + "&" + formData + "&" + search};
this.sendRequest(url, data);
},
queueCalls:function(settings) {
var url = '/example-url-endpoint2';
this.sendRequest(url, settings);
},
addMessage:function(response) {
flashMessage(response.Message, response.Result);
},
addError:function() {
this.errorCount++;
},
sendRequest:function(url, data) {
var blah = this;
j$.ajax({
type: "POST",
url: url,
data: data,
dataType: 'json',
success: function(data) {
response = JSON.parse(data);
if(response.Result != 'error') {
blah.addMessage(response);
} else {
blah.addMessage(response);
blah.addError();
console.log(blah.errorCount);
}
},
error: function(e, textStatus, errorThrown) {
blah.addError();
console.log(blah.errorCount);
alert("There was an error creating the queue");
}
});
}
}
Điều này là do gọi là không đồng bộ, nó cho thấy 0 trước khi lỗi trả về 1. –