【发布时间】:2016-05-12 21:20:19
【问题描述】:
getAjaxPromise(myUrl, true, myType, myContentType, mySuccessFunction, myFailureFunction, myData, true) .then(function(data)
{
//Do something with the data returned form second Ajax call.
//But data returned here is from first ajax.
});
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,
error: errorCallback,
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)
});
}
};
在上面的代码中,当我编写 .then() 时,我得到了第一个 ajax 调用的响应,我不需要第一个 ajax 的响应,而是我想在第一个 ajax 的 then() 中获取 ajax 的响应.
我怎样才能做到这一点?
P.S:我已经编辑了问题并添加了代码以供参考。
【问题讨论】:
-
请向我们展示(在这个问题中)您实际询问的代码。您当前在此处的代码根本没有显示任何 ajax 调用。这个问题需要独立存在,而不是依赖于查看其他问题中的代码。
-
另外,将成功和失败函数传递给返回承诺的东西实际上根本不是设计事物的方式。使用 promise 来处理成功和失败,而不是单独的回调。
-
@jfriend00 实际上我是从移动设备发布的,并且无法格式化代码,因为我看不到格式化工具栏,这就是为什么我提到了我之前提出的代码问题。不过,我已经编辑并添加了这个问题中的代码。
-
@jfriend00 我在上面发布的代码中使用了成功和错误回调,因为我无法在 then() 中获得第二次调用的响应。这就是我问这个问题的原因。如果我能够使用 then() 我不会使用回调。他们在那里是因为我似乎无法在 then() 中获得第二个承诺响应。
-
请查看我发布的答案,因为它显示了使用嵌套承诺并将内部承诺的结果返回给生成的
.then()处理程序的正确方法。您不想按照其他答案中的建议创建额外的延迟,因为这是一种承诺反模式并会产生错误处理问题(请参阅我的答案中的解释)。
标签: javascript jquery ajax promise jquery-deferred