【发布时间】:2013-05-22 21:41:34
【问题描述】:
我有以下简化代码:
$.when(someClass.MethodWithXhrCall(args, callBack, errCallBack))
.then(function () {
console.log('Yep');
}
})
.fail(function () {
console.log('Nope');
});
function callBack(data) {
// Yes I got my data
var x=data.CustomerName;
.....
}
function errCallBack(data) {
alert (data.ErrorText);
}
回调没有被调用。然而,当我不使用延迟构造时,回调按预期工作。当然,我遇到了其他时间问题,我试图避免使用延迟构造。
*于 2013 年 5 月 23 日更新 [已解决] * 我终于能够做我想做的事了。我的回调正在获取响应对象,而延迟对象正在阻塞要执行的代码,直到调用完成。
代码如下:
// Define this as a global variable
var _eipDfd = null; // Will be used to create the deferred object
// Call the webservice to read this customer's data
console.log("Reading existing customer data");
function asyncEvent() {
_eipDfd = new jQuery.Deferred();
someClass.GetCustomer(args, processReadCust, errCallBack);
return _eipDfd.promise();
}
$.when(asyncEvent()).then(
function (status) {
console.log(status); // Will print Success!!
},
function (status) {
console.log(status); // Will print Failed :(
}
);
console.log("Web service call is done");
......
// Callback functions are still being called from someClass.GetCustomer with the response object being pass to them
processReadCust: function (data) {
// Do the work
_eipDfd.resolve("Success!!");
return;
}
errCallBack: function (data) {
// Take care of failure
_eipDfd.reject("Failed :(");
return;
}
【问题讨论】:
-
someClass.MethodWithXhrCall()是否返回承诺或延迟对象? -
为什么不这样做:
someClass.MethodWithXhrCall(args).done(function(response) { ... }); -
或
someClass.MethodWithXhrCall(args).then(callBack, errCallBack);? -
那么,让我们来看看 Beetroot 的实现吧: someClass.MethodWithXhrCall(args).then(callBack, errCallBack);问题是:callBack 和 errCallBack 是否可以访问 Ajax 调用返回的数据?我的问题的原因:在 someClass.MethodWithXhrCall() 中,我以数据作为参数显式调用:callBack (data) 或 errCallBack(data) 如果答案是肯定的,那么问题就解决了。如果没有,那么如何将该信息传递给 callBack 或 errCallBack 函数?
-
我将不得不这样做作为一个正确的答案.....