Ways to ensure certain code is executed every time a promise is resolved in Angular.js

Within my Angular.js application, I am executing an asynchronous operation. To ensure a smooth user experience, I cover the application with a modal div before initiating the operation. Once the operation is complete, regardless of its outcome, I need to remove the div.

Currently, my implementation looks like this:

LoadingOverlay.start(); 
Auth.initialize().then(function() {
    LoadingOverlay.stop();
}, function() {
    LoadingOverlay.stop(); // Duplication of code
})

While this method works effectively, I would prefer a cleaner approach akin to the following pseudo-code:

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

I suspect that this is a common issue, but I have been unable to find any relevant information in the documentation. Is it possible to achieve this? Any suggestions would be greatly appreciated.

Answer №1

The new functionality has been successfully integrated into AngularJS through this specific pull request. Originally named "always," it was eventually changed to finally. Here is an example of how the code should be structured:

LoadingOverlay.start(); 
Auth.initialize().then(function() {
    // This function handles success
}, function() {
    // This function handles errors
}).finally(function() {
    // This section always runs, regardless of success or failure
});

It's important to note that because finally is a reserved word, in some browsers like IE and Android Browser, you may need to treat it as a string to prevent issues:

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

Answer №2

After encountering an error while using Umbraco version 7.3.5 back end and AngularJS version 1.1.5, I came across this helpful thread. When I tried the suggested solution, I received the following error message:

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

Fortunately, I found that replacing finally with always did the trick. In case anyone else running an older version of AngularJS stumbles upon this issue and cannot utilize finally, they can use the following code instead:

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

Answer №3

If you are not utilizing angularJS and are comfortable with handling errors, you can make use of .catch().then() to prevent redundant code repetition.

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

The catch() method could still be beneficial for logging or performing other cleanup tasks. https://jsfiddle.net/pointzerotwo/k4rb41a7/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Node.js program closes immediately upon Java startup

I am building a Discord bot that features a Java FXML interface and utilizes a Node.js program to function as an Audio playing bot. However, I am encountering an issue where the process for Node.js closes immediately when opened in Java. The problem arise ...

The FetchStrategy.FromLocalCache in BreezeJS isn't working as expected and not returning

Something strange is going on here, as I am no longer getting results from the local cache using fetchStrategy. This situation doesn't seem to make sense. Could it be a bug of some sort? Even though the entities are in the cache after the initial qu ...

Tips on comparing a string against an object's value

I need to compare the key values of an object with the strings yes or no. I am encountering difficulties in achieving this comparison and updating radio buttons accordingly based on the comparison. Here is the code snippet: const screenJson = { Managem ...

Leveraging npm packages within a Meteor project through cosmos:browserify

Trying to implement Radium, a JavaScript library for inline CSS, by following the instructions located here. In my app.browserify.js file: Radium = require("radium"); Within package.json: "radium": "0.13.4" Upon attempting to utilize Radium in the app&a ...

The functionality of Node.js's hasOwnProperty method fails to return true even for existing properties

When a user logs into my Node.js Express application using Passport, their user object is saved in the request. Here is an example of what the user object may look like: { "uuid": "caa5cb58-ef92-4de5-a419-ef1478b05dad", "first_name": ...

Finding the Ideal Location for Controllers in an Express.js Project

I'm relatively new to software development and one concept that I find challenging is organizing the directory structure of various projects. As I prepare to embark on an Express project, I prefer keeping controller classes separate from route callbac ...

The Jquery append function is limited to the initial ajax request, necessitating a page refresh in order to populate another div with the desired

When making an AJAX request to retrieve a JSON array, upon successful completion another AJAX request is triggered. The retrieved data is then populated into the div of a bootstrap modal using the jQuery append function. Everything functions as expected ...

How to Use Nested Rows with ng-repeat in Angular?

The code below generates the image displayed: <div class="row" ng-show="result"> <div class="col-sm-12"> <table class="table"> <thead> <tr> ...

Tips for preserving updates following modifications in Angular 5/6?

I'm currently working on enhancing the account information page by implementing a feature that allows users to edit and save their details, such as their name. However, I am encountering an issue where the old name persists after making changes. Below ...

What are the ways to activate an element in vue js?

Is there a way to modify the code so that the function triggers with just one click instead of two? export default { methods: { remove(){ $('.remove-me button').click( function() { removeItem(this); }); ...

Leveraging AJAX for database variable checks and PHP and JavaScript to redirect to specific pages based on the results

I am currently exploring the use of AJAX to validate variables in a database. The goal is to redirect to a specific page if the validation is successful. However, during this testing phase, I am not actually checking any variables. My focus is on verifying ...

When attempting to compile Angular in production mode, errors may arise such as the Uncaught SyntaxError caused by an Unexpected token '<'

I encountered some errors in the console of my Angular 8 app. When I opened the browser window, it was blank and this error appeared: Uncaught SyntaxError: Unexpected token '<' I tried running different ng build commands such as: ng build --b ...

F# Using Ajax Post with JQuery

Attempting to utilize an Ajax Post to communicate with my F# controller in order to invoke a method that outputs a simple string. The ultimate goal is to have data selected via checkboxes on the webpage inserted into a database. Struggling with understand ...

Tips for keeping the Menu bar at the top of the page while scrolling from the middle

I came across a technique mentioned here that I wanted to implement. I used this jsfiddle link (which worked well) to create my own version http://jsfiddle.net/a2q7zk0m/1/, along with a custom menu. However, now it seems like it's not working due to a ...

Creating a regular expression to capture a numerical value enclosed by different characters:

export interface ValueParserResult { value: number, error: string } interface subParseResult { result: (string | number) [], error: string } class ValueParser { parse(eq: string, values: {[key: string] : number}, level?: number) : ValueParse ...

The method for retrieving values and $id from a $firebaseArray using angularJS

Hey there, I'm fairly new to working with Firebase and I seem to be stuck on a problem that I can't find a solution for despite looking in many different places. Here is the structure of my Firebase database: I am trying to retrieve data from a s ...

Make sure the inputs in separate table data cells are lined up in

I need help aligning two input fields in separate td elements to be on the same line. The issue I am encountering is that when an input is added to a td, it covers up any text within the td. https://i.stack.imgur.com/c7GiQ.png There are two scenarios: I ...

What can possibly be the reason why the HttpClient in Angular 5 is not functioning properly

I am attempting to retrieve data from the server and display it in a dropdown menu, but I am encountering an error while fetching the data. Here is my code: https://stackblitz.com/edit/angular-xsydti ngOnInit(){ console.log('init') this ...

Optimizing SEO with asynchronous image loading

I've been developing a custom middleman gem that allows for asynchronous loading of images, similar to the effect seen on Medium. Everything is functioning smoothly, but I'm uncertain about the impact on SEO. The image tag in question looks like ...

What is causing the ajax code to malfunction?

I am new to ASP MVC and trying to create a login form using AJAX. I have written a JsonResult in the controller to check the username and password, but for some reason it is not working. Here is my controller code: public ActionResult login() { ...