It is important to remember that requests cannot always be processed in the order they are sent. Sending multiple requests simultaneously does not guarantee a specific processing sequence. To ensure requests are handled in a specific order, it is necessary to send them sequentially - waiting for each response before sending the next one.
In cases where a request is still pending, you can either disable the button or queue up the next request to be executed once the previous one is completed.
There are different strategies available to manage out-of-sequence issues when sending data, depending on the nature of the data and how it operates on both the client and server side.
One method to ensure requests are processed in order involves queuing any incoming requests while a current request is being processed:
var changeQueue = [];
changeQueue.inProcess = false;
function OnAmountChanged(s, fieldName, keyValue, url) {
if (changeQueue.inProcess) {
changeQueue.push({s:s, fieldName: fieldName, keyValue: keyValue, url: url});
} else {
changeQueue.inProcess = true;
console.log("Get Number: " + s.GetNumber());
console.log(" ");
$.ajax({
type: "POST",
url: url,
data: { key: keyValue, field: fieldName, value: s.GetNumber() },
success: function () {
reloadShoppingCartSummary();
}, complete: function() {
changeQueue.inProcess = false;
if (changeQueue.length) {
var next = changeQueue.shift();
OnAmountChanged(next.s, next.fieldName, next.keyValue, next.url);
}
}
});
}
}
There are also advancements like using promises to handle the queuing process more efficiently. Here's an example in progress: http://jsfiddle.net/jfriend00/4hfyahs3/. This demonstration shows how multiple button presses are queued and executed in order.
Another approach is creating a generic promise serializer function:
// This function ensures serialization of promises
function bindSingle(fn) {
var p = Promise.resolve();
return function(/* args */) {
var args = Array.prototype.slice.call(arguments, 0);
function next() {
return fn.apply(null, args);
}
p = p.then(next, next);
return p;
}
}
function OnAmountChanged(s, fieldName, keyValue, url) {
console.log("Get Number: " + s.GetNumber());
console.log(" ");
return $.ajax({
type: "POST",
url: url,
data: { key: keyValue, field: fieldName, value: s.GetNumber() }
}).then(reloadShoppingCartSummary);
}
var OnAmountChangedSingle = bindSingle(OnAmountChanged);
To utilize this code, replace OnAmountChanged
with OnAmountChangedSingle
in your event handler to enforce serialization.