Reputation: 1438
When I step through mys code in the debugger I can see var answer giving me what I expect but when the function finishes it shows as undefined. Can someone please even point me in the right direction? I've read the docs and can't see where I'm going wrong. Code is as follows:
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);
}
});
}
Thanks in advance
Upvotes: 0
Views: 60
Reputation: 1287
I think its important to remember that hasTimeAccountData
is returning a promise, so it cannot be immediately evaluated with the expectation that it will return the successful result of that promise. So the code you included in your comment (hasTimeAccountData(employee)===false)
won't work.
You need to use the methods of the promise object and introduce callbacks that will respond to the different outcomes of that promise. ie.
hasTimeAccountData(employee)
.then(showEmployeeData, showErrorMessage);
Here is a detailed test case fiddle that I've put together to show one way that you can respond to the different outcomes of the promise. I've expanded hasTimeAccountData
to also invoke promise rejections when things go wrong...
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();
}
I mocked out the callService
method to illustrate the point.
I hope this helps, if not check out the jQuery docs on this, they're really good.
Upvotes: 3