I am looking for the best way to fix this situation. I need additional checks of the returned Ajax data that could cause my _loadPanel
promise operation to "fail":
_loadPanel(url: string, data?: any) : JQueryPromise<any>
{
return $.ajax(
{
url: url,
type: data ? "POST" : "GET",
data: data
}).done(function (html: string, textStatus: string)
{
// Some function that exracts required data
var $panel = extractPanelData(html);
if (!$panel.length)
{
// How to cause a reject here???
}
});
}
You can't do this (below) as the promise returned from Ajax is immutable and it just smells wrong anyway:
var promise = $.ajax({...}).done(function(...)
{
promise.reject("Data failed promise");
});
Is there a simple way of doing this that does not involve adding an extra $.Deferred()
object or is that the only pattern?
Attempts:
I have tried the following, so that I could modify a parent Deferred
object but it will not compile:
var dfd = $.Deferred();
var promise = dfd.promise();
promise = promise.then($.ajax(
{
cache: false,
url: url,
type: data ? "POST" : "GET",
data: data
}).done(...));
It will to allow me to combine an Ajax
promise with a Deferred
promise
Supplied parameters do not match any signature of call target:Type '(value: {}) => {}' requires a call signature, but type 'JQueryXHR' lacks one.
Suggestions?
Something cool:
Not sure how widely known this is, and it does not help this problem (as it also returned an immutable promise), but it appears you can use $.when
to pass initial parameters to the first function
e.g. passing initial parameters to $.ajax
like this:
$.when({
url: url,
type: data? "POST" : "GET",
data: data
}).then($.ajax).done(function (html: string, textStatus: string)
or separate parameters like this:
$.when("Hello!", 22, "There!")
.then(insertPanel);
This can have interesting benefits if the result is chained to previous promises as the Ajax call is not longer run immediately, but only after the previous steps complete.