Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
193
rated 0 times [  196] [ 3]  / answers: 1 / hits: 72308  / 11 Years ago, tue, april 16, 2013, 12:00:00

In my Angular.js application, I'm running some asynchronous operation. Before it starts I cover the application with a modal div, then once the operation is complete, I need to remove the div, whether the operation was successful or not.



Currently I 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 it's quite a common problem, so I was thinking it could be done but cannot find anything in the doc. Any idea if it can be done?


More From » angularjs

 Answers
25

The feature has been implemented in this pull request and is now part of AngularJS. It was initially called always and then later renamed to finally, so the code should be as follow:



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


Note that since finally is a reserved keyword, it might be necessary to make it a string so that it doesn't break on certain browsers (such as IE and Android Browser):



$http.get('/foo')['finally'](doSomething);

[#78870] Monday, April 15, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jarettajb

Total Points: 678
Total Questions: 94
Total Answers: 90

Location: Guernsey
Member since Tue, Jul 6, 2021
3 Years ago
;