• 主页
  • 在使用$q时,angular promise中的catch和finally函数不能工作,但是标准的Promise可以工作--我遗漏了什么?

在使用$q时,angular promise中的catch和finally函数不能工作,但是标准的Promise可以工作--我遗漏了什么?

我想知道为什么使用Angular $q (在1.5.3版本上测试)实现的这个promise在抛出错误时不会执行" catch“和"finally”promise函数(它是由下面示例中的外部try catch捕获的)。然而,如果我用"new Promise()“做同样的事情,它就会(顺便说一句,我正在用最新版本的Chrome测试它)。

运行下面的代码,您可以在其中注入$q (类似于控制器),亲自尝试一下。您将注意到angular promise如何输出try/catch控制台日志(并且永远不会执行finally函数)。而standar promise正确地捕获错误并运行catch()和finally() promise函数:

    var angularPromise = function (data) {
        var defered = $q.defer();
        var promise = defered.promise;
        var emptyvar = null;

        if (data == "fail") {
            //generate the exception
            console.log("code reaches this point");
            var fail = emptyvar.fakeproperty;
            console.log("code will never reach this point due to the exception");
            defered.reject("failed");//neither this...
        }

        return promise;
    }

    var standardPromise = function (data) {
        return new Promise((resolve, reject) => {
            var emptyvar = null;

            if (data == "fail") {
                //generate the exception
                var fail = emptyvar.fakeproperty;
               //in this scenario this error is thrown 
               //and captured by the promise catch() 
               //just as if I would call reject() 
               //which is the expected behaviour
            }

        });
    }

    try {
        angularPromise("fail")
                .then(
                        function (success) {
                            console.log("angularPromise: oka", success)
                        }
                )
                .catch(
                        function (fail) {
                            console.log("angularPromise: fail", fail);
                        }
                ).finally(
                function (fail) {
                    console.log("angularPromise: 'finally' gets excecuted...");
                }
        );
    } catch (e) {
        console.log("angularPromise: exception catched with try/catch and not captured in promise 'catch'. Also 'finally' is never excecuted...");
    }

    try {
        standardPromise("fail")
                .then(
                        function (success) {
                            console.log(" standardPromise oka", success)
                        }
                )
                .catch(
                        function (fail) {
                            console.log("standardPromise: catched as expected", fail);
                        }
                ).finally(
                function () {
                    console.log("standardPromise: 'finally' gets excecuted...");
                }
        );
    } catch (e) {
        console.log("standardPromise exception catched outside promise", e);
    }

转载请注明出处:http://www.jxbyjx.net/article/20230503/928275.html