AngularJS: Surprising presence of undefined within chained outcomes

Encountering a similar issue with nested directives in the past, I was able to implement a workaround. The code snippet that is causing trouble looks something like this:

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: 'Seems 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);

The API service is responsible for making the actual API calls.

The issue arises in the last few lines where console.log(result) displays result.result.openReceipts, and it's evident that result is a Resource object.

I'm perplexed about what could be causing this. Any insights or tips on how to prevent this from happening again?

Answer №1

If you're looking to implement nested promises, it's important to remember that each promise should be returned consistently.

In my opinion, the second "then" in your code snippet seems redundant and could easily be integrated into the first one since there are no promises being returned in the initial "then".

Here is a suggested reorganization of your code:

Pseudo-code:

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

Please let me know if this approach resolves your issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to locate the index of a td element that contains the text "Up" using jQuery, and then utilize that index to choose the corresponding

I have a table that has the following structure: <table> <tr><td>a</td><td>b</td><td>up</td><td>d</td></tr> <tr><td>0</td><td>1</td><td>99</td>< ...

another option besides the nextElementSibling

I have a unique code that applies a style to the following div when another div is clicked, using nextElementSibling. var acc = document.getElementsByClassName("accordion"); var i; for (i = 0; i < acc.length; i++) { acc[i].addEventListener("clic ...

Exploring Angular: Passing ng-model values from ng-repeat to a function and scope

Below is the code snippet: <form ng-submit="addRow($index)"> <input type="text" ng-repeat="column in table.columns" ng-model="column"> <input type="submit" value="add row"> </form> You can see a live example of this code h ...

Navigating from child to parent page in Next.js: how can it be done?

Forgive me if this question seems simplistic, I am new to the world of Next.js and React.js. From my understanding, in Next.js, we can organize pages hierarchically, with each xx_page.js file's path serving as its corresponding url route, as noted in ...

Error: $ is not defined in this Javascript runtime

After inserting a script into my Default.aspx page, I encountered the following error: ...

Pausing briefly after selecting an element with Webdriver

I have been attempting to highlight an element on a webpage for a specific duration of time, approximately 5-6 seconds. However, I am facing difficulty in making the highlight persist for the desired duration as it currently flashes briefly. Despite using ...

add the closing </div> tag using jquery only

Having a slight issue here, it seems that jQuery is being overly clever. Within my HTML code, I am attempting to insert this string into a div container: </div><div class="something"> You'll notice that the closing tag comes first, foll ...

What is the best method to determine if an object includes a specific string?

While I can read values inside the object as the h tags get populated, for some reason I am unable to hit the statements checking response.image for a value, despite confirming its existence through console.log. I'm not entirely sure if the code belo ...

Despite successfully making a request to the API, a CORS error is still occurring in the .NET Core web API

In my current project, I am working on an Angular CLI app with Angular 4 while connecting it to a new .NET Core API project. The environment I am using is Windows 7 and the default browser in my organization is IE 11. Although I need it to work perfectly o ...

Utilize ng-show/ng-hide to dynamically display messages or content based on the results obtained

One of my functions builds and returns a JSON object like this: {"message":"No Grupos de MetaDetalles found","entities":[],"breadcrumbs":[],"parent_id":0} Now, I have an Angular view set up like this: <table id="example-datatables" class="table table ...

Trigger function in React before closing window or tab

I need assistance with calling a function when the user closes the tab on the window. Through my research, I came across using window's beforeunload event to achieve this: componentDidMount(){ window.addEventListener('beforeunload', (ev) ...

What is the best way to update the src of an input using an onclick event?

When I click the input, my background changes color as expected. However, the src of the input only changes on the second click. How can I make it change the source on the first click? Also, how can I change the src back to the original with a second cli ...

Encountering a d3.js runtime issue following the transition to Angular 8

I've been experimenting with upgrading my Angular 6 application to Angular 8. It compiles fine, but I'm facing a runtime error as soon as it runs: "d3.js:8 Uncaught TypeError: Cannot read property 'document' of undefined". The specific ...

Choose a random element from an array and then modify the array

Can someone please assist me with this task? I am creating an array that corresponds to specific question numbers. var arrayCharge = []; for (var i = 2; i <= 45; i++) { arrayCharge.push(i); } I then utilize these numbers to display the respective quest ...

Angular2+ does not return any elements when using .getElementsByClassName() even if they are present

I have a question that seems simple, but I can't seem to find the answer anywhere. I've looked through past questions but still haven't found a solution... In my Angular template, there is a large amount of text inside a div, and some parts ...

Maintaining original coordinates while merging meshes in three.js

I'm working with threejs and my goal is straightforward. I aim to achieve the following: Create two cubes positioned with a 1 cube-wide gap in between Combine them into a single geometry object using geometry.merge Unfortunately, despite hours of e ...

Generate a sequence of years without relying on the range function

Is there a different approach to generating this array without relying on the range function? Below is an illustration of what I want, but without utilizing the range method. const years = myCustomArrayGeneration(1990, getYear(new Date()) + 1, 1); ...

I am receiving data but ng-repeat is not binding the event as expected

Welcome, I am still learning AngularJS and have encountered a situation where I am calling a WebApi webservice. Interestingly, I have two pages - one that binds data and another that doesn't, even though the code is the same on both pages. Upon checki ...

Ensuring all functions have finished executing and sending a response in Node.js - best practices

Below is the code snippet: route.get('/',function(req, res){ for(var e = 0; e < contactEmailArray.length; e++){ var currentContact = contactEmailArray[e]; setSentEmailCount(gmail, currentContact); setReceivedEmailCou ...

Two clicks are necessary for this unique Javascript function to execute

Being new to javascript, I am a rails developer with limited experience. In my rails 3 app, I have integrated joyride, a jquery plugin that displays messages to users for a page tour when the page loads. The following script successfully runs the tour on p ...