Idkt
Idkt

Reputation: 2996

AngularJS: Unexpected undefined in chained results

I've come across this issue before with nested directives, but I managed to find a workaround there. I have code that looks a bit like,

var token = API.callGeneric({}, {method: 'kds.getTokenExtended2', params: ['demo', 'demo', '', '', '', '', '', false, '', '']}); //kds.
token.$promise
.then(function (result) {
    if (!angular.isUndefined(result.error)) { // API error
        $scope.msg = {iconClass: 'glyphicon-exclamation-sign', txt: 'Looks like there was a problem.'}
        if (!APIErr.handle(result.error)) { // handle also returns continueExec flags
            return;
        }
    }
    $scope.msg = {iconClass: 'glyphicon-cloud-download', txt: 'almost there…'};
    $scope.token = result.result;
    console.log('result', result.result);
}, function (error) { // server error
    $scope.msg = {iconClass: 'glyphicon-exclamation-sign', txt: 'issues with server, summoning the gods'}
    APIErr.handle(error);
})

.then(function (result) {
    $scope.msg = {}; // clear the message
    // another api call to get bills
    return API.callGeneric({}, {method: 'kds.getKitchenDisplayReceipts', params: [$scope.token, new Date().getTime()]});
}, APIErr.handle)

.then(function (result) {
    console.log(result); // can see result.result.openReceipts
    var receiptIds = result.result.openReceipts; // undefined?
}, APIErr.handle);

And API is a service that calls the API, obviously.

The problem is the last few lines, where console.log(result) shows result.result.openReceipts, and obviously result is a Resource object.

I'm stumped about what might be going on here. Any clues? How can I avoid this in future?

Upvotes: 0

Views: 122

Answers (1)

Wawy
Wawy

Reputation: 6269

If you want to nest promises you need to return a promise every time.

Your second then is unnecessary in my opinion and could be done inside the first one as the first one is not returning any promises.

So it could be something like:

Pseudo-code:

API.call('token').then(function(result) {
 ...
 return API.call('displayreceipts');
})
.then(function(result){
  var recieptIds = result.result.openReceipts;
})

Let me know if it works.

Upvotes: 1

Related Questions