当我在调试器中遍历mys代码时,我可以看到var答案,给出了我所期望的结果,但是当函数完成时,它显示为未定义的。有人能帮我指出正确的方向吗?我已经看过医生了,我看不出哪里出了问题。守则如下:
function hasTimeAccountData(aktivEmployee) {
this.aktivEmployee = aktivEmployee;
var deferred = new $.Deferred();
callService("GetEmployee",
{ employeeNo: aktivEmployee.id},
function (result) {
var answer = result.HasTimeAccountData;
deferred.resolve(answer);
});
return deferred.promise();
}
function callService(functionName, data, onSuccess, onTimeout) {
var timeout;
if (onTimeout) timeout = setTimeout(onTimeout, 10000);
var server = lStorage.getServerUrl();
if (!server) server = getDefaultAddress();
var url = server + functionName;
$.ajax({
dataType: "jsonp",
url: url,
data: data,
success: function (data) {
clearTimeout(timeout);
if (onSuccess) onSuccess(data);
}
});
}提前感谢
发布于 2014-03-18 13:20:45
我认为重要的是要记住,hasTimeAccountData正在返回一个承诺,因此不能立即评估它是否会返回该承诺的成功结果。因此,您在注释(hasTimeAccountData(employee)===false)中包含的代码将无法工作。
您需要使用诺言对象的方法,并引入回调,以响应该承诺的不同结果。即。
hasTimeAccountData(employee)
.then(showEmployeeData, showErrorMessage);这里是一个详细的测试用例小提琴。,我把它放在一起,向您展示了一种方法,您可以对承诺的不同结果做出反应。我已经扩展了hasTimeAccountData,当事情出错的时候,我也会引用拒绝承诺的话.
function hasTimeAccountData(aktivEmployee) {
var deferred = new $.Deferred();
this.aktivEmployee = aktivEmployee;
callService(
"GetEmployee",
{ employeeNo: aktivEmployee.id },
function success(result) {
if (result.hasOwnProperty("HasTimeAccountData")) {
deferred.resolve(result.HasTimeAccountData);
}
else {
deferred.reject("no time account data field in return data!");
}
},
function timeout() {
deferred.reject("timeout occurred");
}
);
return deferred.promise();
}为了说明这一点,我模拟了callService方法。
我希望这有帮助,如果不检查关于这个的jQuery文档,他们真的很好。
https://stackoverflow.com/questions/22478996
复制相似问题