When interacting with a server using JavaScript in my single-page browser application, I aim to implement a callback function that will always be executed after receiving a response from the server, regardless of whether it was successful or resulted in an error.
There are two specific scenarios where I require this functionality:
1) I need to disable a "save" button while waiting for the server's response and re-enable it once the server replies, whether with an error or success message.
2) I am utilizing a polling mechanism and want to avoid sending multiple requests to the server if there is a delay in the response. I prefer to wait for one poll call to complete before initiating another.
Currently, I have a workaround where I include two functions (one for success and one for error) as options in a lengthy method chain. However, I find this approach to be fragile and cumbersome (pseudo code example):
function doCall() {
framework1.callit({success : myCallback, error : myCallback})
};
framework123.callit = function(options) {
options = options || {};
if (options.error) {
var oldError = options.error;
options.error = function(errorStuff) {
// handle error stuff within callit
oldError(errorStuff);
} else {
// handle error stuff within callit
}
generalCallFunction(options);
}
function generalCallFunction(options) {
options = // ... further processing to ensure handling of success and error scenarios, along with additional options
ajax( blah, blah, options);
}
I also experimented with a backbone solution where I listen to sync events and an error callback following a similar pattern as above.
I often worry about losing track of the error or success functions within this complex setup, making it challenging to follow the logic.
Are there any frameworks or design patterns that can simplify this process? Is it unconventional to have universal actions that should occur regardless of the outcome being an error or success?