Error: Trying to access the `then` property of an undefined value is not allowed

I'm struggling with this code and need some fresh eyes to help me find the missing piece.

   $scope.checkout = function (form) {
        //some code here

        function checkoutErrorHandler(error) {
          //some code here
        }

        function displaySuccessMessage() {
            $scope.success = true;
            cartService.emptyCart();    
        }

        checkoutService.makePayment($scope.payment).then(function (i) {

            //some code here
            checkoutService.buyProducts($scope.payment, products, i).then(function () {
                    displaySuccessMessage().then(function(){
                        $scope.payment = {}; // clear checkout form
                        $scope.form.reset();
                    });
                    return displaySuccessMessage;
                },
                checkoutErrorHandler
            );
        }, checkoutErrorHandler);
    };

I keep running into a "Cannot read property 'then' of undefined" error when I try to call displaySuccessMessage. Despite my efforts to refactor, it's still not working. Can anyone spot what I'm missing?

Answer №1

The function displaySuccessMessage is currently not set up to return a promise or anything at all.

If you assume that cartService.emptyCart() does return a promise, you can update displaySuccessMessage as follows to ensure it functions correctly:

    function displaySuccessMessage() {
        $scope.success = true;
        return cartService.emptyCart();
    }

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

Can someone help me identify the table rows that are adjacent to a dropped row in a jQueryUI Sortable setup?

My current setup involves using the jQueryUI Sortable plugin on a table, and thankfully everything appears to be functioning correctly. Both the HTML and JavaScript are passing validation. However, I am faced with the challenge of finding a way to identi ...

Initialization of Arrays with Default Values

I have taken on the task of converting a C++ program into JavaScript. In C++, when creating a dynamic array of type float/double, the entries are automatically initialized to 0.0; there is no need for explicit initialization. For example, a 1-D vector of ...

Custom directives in AngularJS do not have the capability to function with the ui-sref

Initially, this code snippet proves successful: <a ui-sref="students({courseId: $ctrl.Course.Id})">{{ student.Name }}</a> Showing that the router is functioning properly. A custom directive is then created: link: "=link" <div ng-if="$ctrl. ...

Having difficulty identifying duplicate sentences in Vue.js when highlighting them

I am looking for a way to identify and highlight repetitive sentences within a text area input paragraph. I attempted the following code, but unfortunately, it did not produce the desired result. highlightRepeatedText(str) { // Split the string into an ...

Unable to make calls to functions within my JQuery prototype class

When it comes to setting up the behavior for my content_item elements, I use the following approach: $.fn.createContentItem = function() { $(this).selectItem = function() { $(".content_item").removeClass("selected"); $ ...

What is the best way to extract data from a textarea HTML tag and store it in an array before iterating through it?

I have a project in progress where I am developing a webpage that will collect links from users and open each link in a new tab. I am using the <textarea> tag in HTML along with a submit button for link collection. Users are instructed to input only ...

Leveraging promises with node.js and couched/nano for asynchronous operations

Currently experimenting with the Q promises library in conjunction with couchDB and Nano. The code below is able to display messages in the console, however, it seems that the database is not being created as expected. var nano = require('nano') ...

The error message reads: `'Icon' is not included in the export list of 'antd'`

I have recently developed a React application and I'm incorporating Ant Design (antd) into it. However, I encountered an issue in one of my project files where I am unable to use the Icon tag. It seems like this is a known problem in ANT V4. The impo ...

Encountering an error in Express while attempting to upload an image due to the inability to read the property 'file' of undefined

I am currently learning Express framework. I encountered an error while trying to upload an image using Express. The error message I received is "Cannot read property 'file' of undefined." Below are the code snippets that I am using, and I&apo ...

Angular 5 - Strategies for excluding specific properties from Observable updates

Currently, I am in the process of developing a webpage where users can view and like various videos. The video content and user likes are stored in a database, and I have implemented two Angular services for handling data retrieval and storage. However, I ...

Replace the <button> tag with an <input> tag that triggers an onclick event

I am struggling to swap one element for another using an "onclick()" function. I can create new elements, but that doesn't solve my problem. Imagine I have a element that I want to replace with a different element on the same spot. I am familiar w ...

Exporting multiple HighCharts visualizations to PowerPoint presentations

Our team is preparing to create an Angular-based web application featuring 15-20 unique charts utilizing HighCharts. One of the key requirements is the ability to export these charts into PowerPoint slides. We are aware that HighCharts offers an option to ...

Guide on looping through an array of objects and displaying the key and value pairs using pug

I'm having trouble displaying errors from an incomplete form. In my array of objects, I want to iterate through and retrieve the errors, but it seems the list is currently empty. Upon debugging, it appears that the errors variable contains [ { e ...

Angular's handling of cached data returned from HTTP requests experiencing issues

In my controller, I have the following code snippet: var cache = $cacheFactory('contacts'); var data = cache.get('contacts'); if(!data) { Contacts.get() .success(function(result) { data = result; c ...

What are some methods for monitoring time in PHP on the client and server sides?

I am in the process of developing an exam system using the Laravel Framework for PHP. The system will allow students to take exams within a specified time frame. For instance, if an exam is scheduled to start at 13:00 (my local time) and last for 2 hours, ...

Trouble with AngularJS not redirecting to home page after logging in

My current setup involves spring + angularJS, and I'm facing an issue where after authentication from the controller, I'm unable to redirect to the home page. console.log("id:"+employee.id); alert("Attempting to redirect to the home page") ...

What impact does rotation have on an orthographic camera within the Three.js framework?

I am working in Three.js with a scene that includes a plane and an orthographic camera. Orthographic camera at -90deg: When the camera is rotated to -90 deg on the x-axis (looking straight down from above), only the plane is visible in the view. Scene s ...

Exploring the Difference Between Passing 0 and an Empty Array as the Second Argument in useEffect with React Hooks

Recently, I came across someone using 0 instead of an empty array for the second argument in useEffect. Instead of the typical: useEffect(() => { console.log('Run once'); }, []); they had: useEffect(() => { console.log('Run o ...

Utilizing nested array object values in ReactJS mappings

My JSON API is set up to provide a data structure for a single record, with an array of associations nested within the record. An example of the response from the api looks like this: { "name":"foo", "bars":[ { "name":"bar1" ...

Is it possible to use the setState function in a React functional component when the form is loading

Implementing a React component using hooks: Requirement: Upon page load, data should populate from the backend into dropdowns and tables with checkboxes. When the Submit button is clicked, the consolidated object of default selected values should be used ...