AngularJS: promises, can you pass on the promise after using .then ()?

I'm still new to Angular and promises, so hopefully I have the right idea here.

I currently have a data-level service that uses restangular to get some data, and then returns a promise like this ...

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

Then my controller that called this function gets a promise back like this ...

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

This works well, but I would like to use the promise inside my data store before transferring it back. I would like to use the .then () method to check if it worked and make some entries, then, from the sucess function and from the failure function, I would like to return the original promise back to my controller.

.then(), , , , , .

- -, , datastore...

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

};
+4
1

. Promises :

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, . convicene, $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;
    });

};
+8

Source: https://habr.com/ru/post/1533380/


All Articles