AngularJS: promises,你能在使用.then()之后传递一个promise吗?

AngularJS : promises, can you pass a promise back after using .then()?

本文关键字:一个 promise 之后 AngularJS then promises      更新时间:2023-09-26

我仍然是Angular和promises的新手,所以我希望我在这里有正确的想法。

我现在有一个数据层服务,它使用reangular来获取一些数据,然后返回一个承诺,像这样…

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;
    });
};

在您的伪代码中,您实际上一点也不差。承诺链:

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); 
    });
};

控制器现在以相同的值被解析/拒绝。日志要求访问承诺,因此您必须添加一个.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;
    });
};