Javascript Promise - TypeError:无法读取未定义的属性“then”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26151312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:24:47  来源:igfitidea点击:

Promise - TypeError: Cannot read property 'then' of undefined

javascriptangularjspromise

提问by Paul Erdos

I think I just need another pair of eyes on this, because I can't get what I'm missing here.

我想我只需要另外一双眼睛,因为我无法得到我在这里缺少的东西。

   $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 get "Cannot read property 'then' of undefined" when I call displaySuccessMessage. I've tried refactoring several different ways but cannot get it to work. Does anyone see my mistake?

当我调用 displaySuccessMessage 时,我收到“无法读取未定义的属性‘then’”。我试过重构几种不同的方式,但无法让它工作。有没有人看到我的错误?

回答by Shomz

Your displaySuccessMessagedoes not return a promise. In fact, it doesn't return anything.

displaySuccessMessage不返回一个承诺。事实上,它不会返回任何东西。

Assuming that cartService.emptyCart()returns a promise, you can modify displaySuccessMessagelike this and it should work just fine:

假设cartService.emptyCart()返回一个 promise,你可以displaySuccessMessage像这样修改它应该可以正常工作:

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