How to always run some code when a promise is executed in Angular.js

In my Angular.js application, I run some asynchronous operation. Before starting, I cover the application with a modal div, and then, once the operation is complete, I need to remove the div whether the operation was successful or not.

I currently have this:

LoadingOverlay.start(); Auth.initialize().then(function() { LoadingOverlay.stop(); }, function() { LoadingOverlay.stop(); // Code needs to be duplicated here }) 

It works well, however I would prefer to have something cleaner like this pseudo code:

 LoadingOverlay.start(); Auth.initialize().finally(function() { // *pseudo-code* - some function that is always executed on both failure and success. LoadingOverlay.stop(); }) 

I assume this is a fairly common problem, so I thought it could be done, but could not find anything in the document. Any idea if this can be done?

+75
javascript angularjs promise deferred finally
Apr 16 '13 at 14:52
source share
4 answers

This function was implemented in this pull request and is now part of AngularJS. It was originally called β€œalways,” and then renamed to finally , so the code should look like this:

 LoadingOverlay.start(); Auth.initialize().then(function() { // Success handler }, function() { // Error handler }).finally(function() { // Always execute this on both error and success }); 

Please note that since finally is a reserved keyword, you may need to make it a string so that it does not break in some browsers (for example, in IE and Android):

 $http.get('/foo')['finally'](doSomething); 
+146
May 23 '13 at 14:23
source share

I am using Umbraco version 7.3.5 using EndularJS version 1.1.5 and found this thread. When I executed the approved answer, I received an error message:

xxx (...), then (...). finally not a function

However, the work was always . If anyone else using the old version of AngularJS finds this thread and cannot use finally , use this code instead

 LoadingOverlay.start(); Auth.initialize().then(function() { // Success handler }, function() { // Error handler }).always(function() { // Always execute this on both error and success }); 
+5
Feb 25 '16 at 13:12
source share

I would use ngView to render the contents of the page and trigger the removal of the modality of the $ viewContentLoaded event. See http://docs.angularjs.org/api/ng.directive:ngView for this event and http://docs.angularjs.org/api/ng . $ rootScope.Scope for the $ on event listener.

+1
Apr 17 '13 at 8:31
source share

For those who don't use angularJS, and if you're fine with catching the error (not sure if .finally () does this), you can use .catch (). then () to avoid code duplication.

 Promise.resolve() .catch(() => {}) .then(() => console.log('finally')); 

Trap () may be useful in any case for logging or other cleanup. https://jsfiddle.net/pointzerotwo/k4rb41a7/

0
Jul 19 '17 at 16:00
source share



All Articles