My understanding of how to chain promises is still not completely solid. What I am trying to achieve is as follows:
I have a promise that can either resolve or reject. The following code checks for this and continues if the promise resolves, or stops if it rejects. However, I simply want to run this promise without worrying about its outcome.
The way I used to do it was:
function a(){
return Service.doSomething();
}
So I wrapped it in another promise and here's the result:
function a(){
var q = $q.defer();
Service.doSomething(); // I don't even need to handle whatever the outcome is
q.resolve();
return q.promise;
}
(Yes, this is from an Angular project)
Although this works, it doesn't look very elegant. Is there a better or cleaner way to write this?
Update: I understand that this behavior might seem strange, so let me explain a bit more.
This example pertains to Angular routes and my custom middleware for authentication handling.
I've created three special "route" handlers:
- customRoute
- onlyGuest
- onlyUser
Instead of writing
$routeProvider.route({});
I write (for example)
$routeProvider.customRoute({});
Each of these special route handlers extends the resolve attribute of the route with authentication logic.
For instance, I can do the following:
$rootScope.$on('$routeChangeError',function(e, current, previous, rejection){
// Only for logged in users
if (rejection && rejection.needsAuthentication){
$rootScope.refUrl = $location.path();
$location.path('/user/login');
}
// Only for non-logged in users
if (rejection && rejection.isOnlyGuest){
$rootScope.refUrl = $location.path();
$location.path('/dashboard');
}
});
The functions onlyGuest and onlyUser are self-explanatory, but I also have customRoute() which essentially runs the authentication method to retrieve user info when a user accesses the app directly through this URL, whether they are a guest or logged in.
The issue arises when the authentication method throws a reject(). This triggers the route change error. Therefore, for customRoute(), I need to run the authentication process without triggering the changeError – always resolving as true even if the authentication()'s promise rejects.
I hope this clarifies things rather than confusing them further...