Working With Ajax Promises / Deferred
I am trying to get an Ajax promise using the code below. Because my function makes another ajax call before initiating the actual one , for getting the authKey, The promise (that s
Solution 1:
you forgot to return the getTokenPromiseFromServer if isSecureCall is true your function return null
self.getAjaxPromise = function(url, async, type, contentType, successCallback,
errorCallback, data, isSecureCall)
{
if (isSecureCall) {
returngetTokenPromiseFromServer().then(function(tokenData) {
return $.ajax({
beforeSend: function(request) {
request.setRequestHeader("authKey", tokenData.key);
},
url: url,
async: async,
type: type,
contentType: contentType,
success: successCallback, //Success callback runs fine, then() does noterror: errorCallback, //Error callback runs fine, then() does notdata: JSON.stringify(data)
});
});
} else { //Just one ajax call return $.ajax({
beforeSend: function(request) {
request.setRequestHeader("authKey", "anonymous");
},
url: url,
async: async,
type: type,
contentType: contentType,
success: successCallback,
error: errorCallback,
data: JSON.stringify(data)
});
});
}
};
Solution 2:
You had forgot to return the promise inside the if statement, you are return it only on else, the fixed code below:
self.getAjaxPromise = function(url, async, type, contentType, successCallback,
errorCallback, data, isSecureCall) {
if (isSecureCall) {
var tokenPromise = getTokenPromiseFromServer(); //Another Ajax call to get latest token from service
tokenPromise.then(function(tokenData) {
return $.ajax({
beforeSend: function(request) {
request.setRequestHeader("authKey", tokenData.key);
},
url: url,
async: async,
type: type,
contentType: contentType,
success: successCallback, //Success callback runs fine, then() does noterror: errorCallback, //Error callback runs fine, then() does notdata: JSON.stringify(data)
});
});
return tokenPromise;
} else { //Just one ajax call return $.ajax({
beforeSend: function(request) {
request.setRequestHeader("authKey", "anonymous");
},
url: url,
async: async,
type: type,
contentType: contentType,
success: successCallback,
error: errorCallback,
data: JSON.stringify(data)
});
});
}
};
Solution 3:
You forgot to return tokenPromise you must return it from first if
if (isSecureCall) {
var tokenPromise = getTokenPromiseFromServer(); //Another Ajax call to get latest token from service// ...return tokenPromise;
}
Post a Comment for "Working With Ajax Promises / Deferred"