Search code examples
javascriptangularjsajaxpromiseangularjs-service

Is this a common pattern? (returning data instead of returning a promise)


I encountered this pattern in the book 'Mean Machine'.

Until now, I thought you always return a promise from a service (to a controller), then you deal with .success or .then in your controller.

Here, the author is returning the returned data from the promise.

Is this common? Is it recommended practice?

  .factory('Auth', function($http, $q, AuthToken) {

        var authFactory = {};

        authFactory.login = function(username, password) {
            return
                $http
                    .post('/api/authenticate', {
                        username: username,
                        password: password
                    })
                    .success(function(data) {
                        AuthToken.setToken(data.token);
                        return data;
                    });
        };
        ...

Solution

  • Yes, I would recommend such a solution and consider it a good practice. In @scniro response you would need to specially handle error response as well which adds on complexity. Your solution is much cleaner, shorter, and easier to read. I have found a good article about it here http://blog.ninja-squad.com/2015/05/28/angularjs-promises/