javascript - Angular Promises - 从成功跳转到失败回调?

标签 javascript angularjs angular-promise

我觉得我可能正在做一些 Promises 不打算做的事情,但我们开始吧,这就是我想做的:

$http.get('/api/endpoint/PlanA.json').then(
    function success( response ) {
        if ( response.data.isAllGood ) {
            $scope.myData = response.data;
        }
        else {
            // TODO HERE! Call the failure function!
        }
    },
    function failure() {
        $http.get('/api/endpoint/PlanB.json').then(
            function planBsuccess( response ) {
                $scope.myData = response.data;
            }
        );
    }
).then(function doOtherStuff() {});

如果 PlanA 端点返回 404 或 500...,这将按预期工作,但如果它成功,但有错误数据(例如,isAllGood 是false),那么我希望它能到达失败回调。有没有简单的方法可以做到这一点?

我试过调用 $q.defer().reject 并返回那个 promise,但是这只是调用了 doOtherStuff 的失败回调。

最佳答案

是的,有一种简单的方法可以做到这一点。您只需将失败回调链接到成功回调之后,而不是紧挨着它 - 参见 When is .then(success, fail) considered an antipattern for promises?以获得更详细的解释。

$http.get('/api/endpoint/PlanA.json').then(function success(response) {
    if (response.data.isAllGood) {
        $scope.myData = response.data;
    } else {
        return $q.reject(); // fail this promise
    }
}).catch(function failure() { // and handle it here (also errors originating from $http)
    return $http.get('/api/endpoint/PlanB.json').then(function planBsuccess(response) {
//  ^^^^^^ don't forget to wait with doOtherStuff for plan B
        $scope.myData = response.data;
    });
}).then(function doOtherStuff() {});

或者甚至更好,避免 $scope 赋值的代码重复:

$http.get('/api/endpoint/PlanA.json').then(function validate(response) {
    if (response.data.isAllGood)
        return response;
    else
        throw new Error("noGoodData");
}).catch(function failure() {
    return $http.get('/api/endpoint/PlanB.json');
}).then(function success(response) {
    $scope.myData = response.data;
    return doOtherStuff();
});

关于javascript - Angular Promises - 从成功跳转到失败回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29924966/

相关文章:

javascript - 如何使用 php 从 html 行(在表中)获取数据

字符串输出中的Javascript变量?

css - Ionic Framework 中收集重复项的动画

javascript - JS promise/async 澄清问题

javascript - Ionic Angular/为什么在 Controller 功能结束之前不调用服务

javascript - 如何在 Angular 1.5 中重置表单

javascript - 如果输入为空或包含值则切换类 - Javascript

javascript - 指令中的 AngularJS 模板函数给出错误 'Template for directive must have exactly one root element'

javascript - adalProvider.init(..) 破坏路由

javascript - Promise 在解决之前不等待嵌套 promise