【问题标题】:AngularJS : promises, can you pass a promise back after using .then()?AngularJS:promise,你能在使用 .then() 后将 promise 传回去吗?
【发布时间】:2014-05-03 18:04:51
【问题描述】:

我对 Angular 还是很陌生,所以我希望我在这里有正确的想法。

我目前有一个数据层服务,它使用restangular来获取一些数据,然后返回一个promise,就像这样......

dataStore.getUsers = function (params) {
    return users.getList(params);
};

然后,调用此函数的我的控制器收到一个承诺,就像这样......

$dataStore.getUsers(params).then(function (response) {
    $scope.users = response;
}, function(response) {
    $log.error("Get users returned an error: ", response);
});

这很好用,但我想在将它传回之前在我的数据存储中使用它。我想使用 .then() 方法检查它是否失败并进行一些日志记录,然后,从成功函数和失败函数中,我想将原始承诺返回给我的控制器。

然后我的控制器将能够像现在一样使用 .then() 方法,事实上,我根本不希望我的控制器代码改变,只是我的数据存储代码。

这里有一些半伪代码来显示我希望我的数据存储功能做什么...

dataStore.getUsers = function (params) {

    users.getList(params).then(function (response) {
        $log("server responded")
        return original promise;
    }, function(response) {
        $log.error("server did not respond");
        return original promise;
    });

};

【问题讨论】:

    标签: javascript angularjs promise restangular angular-promise


    【解决方案1】:

    实际上,您的伪代码并不遥远。承诺链:

    dataStore.getUsers = function (params) {
        return users.getList(params).then(function (response) {
            $log("server responded")
            return response;
        }, function(failure) {
            $log.error("server did not respond");
            // change to throw if you want Angular lever logs
            return $q.reject(failure); 
        });
    
    };
    

    控制器现在被解析/拒绝为相同的值。日志需要进入promise,所以你必须添加一个.then处理程序来处理它。其他 Promise 库为此提供了实用的方法,但 $q 在这方面是极简的。

    或者,您可以使用更好的 catch 语法,并将错误传播到您的日志:

    dataStore.getUsers = function (params) {
        return users.getList(params).then(function (response) {
            $log("server responded")
            return response;
        }).catch(function(failure) {
            $log.error("server did not respond");
            throw failure;
        });
    
    };
    

    【讨论】:

    • 如果您必须返回原始承诺,您也可以这样做var p = users.getList(...); p.then(... log code ...); return p,但确实没有充分的理由更喜欢这样做。
    • .catch 之前缺少一个括号
    • @thefourtheye 这正是编辑的目的:P 请随意编辑我的代码,以便下次修复此类问题 :)
    • 其实,如果你在 5 分钟内编辑,SO 不必维护编辑历史:)
    • 感谢本杰明,这正是我想要的。我缺少的一点是您可以将整个东西退回。即使我不知道 angular catch 的作用,我也会使用第二个版本。我相信稍后会明白为什么这是一个好主意:)
    猜你喜欢
    • 2019-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 2021-08-07
    • 2020-06-01
    • 1970-01-01
    相关资源
    最近更新 更多