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?
defer() to create a Promise. A Promise is a function that returns a single value or error in the future. So whenever you have some asynchronous process that should return a value or an error, you can use $q. defer() to create a new Promise.
Promises in Angular provide an easy way to execute asynchronous functions that use callbacks, while emitting and completing (resolving or rejecting) one value at a time. When using an Angular Promise, you are enabled to emit a single event from the API.
Promises in AngularJS are provided by the built-in $q service. They provide a way to execute asynchronous functions in series by registering them with a promise object. {info} Promises have made their way into native JavaScript as part of the ES6 specification.
A promise is a placeholder for a future value. It serves the same function as callbacks but has a nicer syntax and makes it easier to handle errors.
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);
I'm using Umbraco version 7.3.5 back end with AngularJS version 1.1.5 and found this thread. When I implemented the approved answer I got the error:
xxx(...).then(...).finally is not a function
What did work however was always
. If anyone else using an old version of AngularJS finds this thread and can't 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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With