I am trying to be a good jQuery citizen, and embrace promises, but some basic usage still escapes me.
The code below is a panel loading method, that may receive a request to redirect to another page instead of load the original one specified. The redirect is under sever control (e.g. based on previous user 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 says to redirect
if (location)
{
// Chain to the new load request
// **** WHAT TO DO HERE WITH RETURNED PROMISE ***
THIS._loadNewPanel(location, null);
}
else
{
dfd.resolve(html);
}
}).fail((jqXHR, textStatus: string, errorThrown: string) =>
{
dfd.reject(errorThrown + ": " + url);
});
return promise;
}
Is it a case of simply adding .done()
to the recursive call like this and pass back the results?
// Chain to the new load request
THIS._loadNewPanel(location, null).done(function(html){
dfd.resolve(html);
}).fail(function(error: string){
dfd.reject(error);
});
Is there a sleeker way of writing the whole thing? Am I abusing jQuery promises?