使用Ajax承诺/推迟 [英] Working with Ajax Promises / Deferred
问题描述
我正在尝试使用以下代码获取Ajax promise
.因为我的函数在启动实际的ajax调用之前进行了另一个ajax调用,以获取authKey
,所以实际调用中的promise (应该已返回)为null,&我不能在其上使用.then()
,因为我认为我没有得到任何回报.我不知道为什么.
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 should have been returned) from the actual call is null, & I cannot use .then()
on it because I think I am not getting anything in return from it. I am not sure why.
我在这里做错了什么?还有其他方法可以解决此问题.我像下面提到的那样调用getAjaxPromise(),但返回null:
What am I doing wrong here? Is there any other way to go about this. I call getAjaxPromise() like mentioned below but get null in return:
getAjaxPromise(myUrl, true, myType, myContentType, mySuccessFunction, myFailureFunction,
myData, true)
.then(function(data) //.then() gives undefined-null error
{
//Do something with the data returned form actual Ajax call.
});
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) { //This then runs fine
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 not
error: errorCallback, //Error callback runs fine, then() does not
data: 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)
});
});
}
};
推荐答案
您忘记了返回getTokenPromiseFromServer
如果isSecureCall为true,则函数返回null
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) {
return getTokenPromiseFromServer().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 not
error: errorCallback, //Error callback runs fine, then() does not
data: 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)
});
});
}
};
这篇关于使用Ajax承诺/推迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!