I'm making an effort to adhere to good jQuery practices and utilize promises, but I still struggle with some basic concepts.
Below is a panel loading method that might need to redirect to another page instead of loading the originally specified one. This redirection is determined by the server (e.g., based on the user's previous response).
private _loadNewPanel(url: string, data?: any): JQueryPromise<any>
{
var THIS = this;
var dfd = $.Deferred();
var promise = dfd.promise();
$.ajax({
cache: false,
url: url,
type: data ? "POST" : "GET",
data: data
})
.done((html: string, textStatus: string, jqXHR: JQueryXHR) =>
{
var location = jqXHR.getResponseHeader('redirect-url');
// Server indicates a need to redirect
if (location)
{
// Continue with the new load request
// **** WHAT SHOULD BE DONE HERE WITH THE RETURNED PROMISE ***
THIS._loadNewPanel(location, null);
}
else
{
dfd.resolve(html);
}
}).fail((jqXHR, textStatus: string, errorThrown: string) =>
{
dfd.reject(errorThrown + ": " + url);
});
return promise;
}
Could simply adding .done()
to the recursive call like this and returning the results be a solution?
// Continue with the new load request
THIS._loadNewPanel(location, null).done(function(html){
dfd.resolve(html);
}).fail(function(error: string){
dfd.reject(error);
});
Is there a more concise way to write this code? Am I overcomplicating things with jQuery promises?