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

Navigating through pages in a server component using Next.js

I am currently working on a project that involves implementing pagination using the NextJS 13 server component without relying on the use client. The goal is to ensure that when a button is clicked, new entries are added to the screen in a sequential order ...

The variable continuously updates itself inexplicably, without any specific code dictating it to

In the sandbox-based game I am playing, two variables are present. blocks (this is an array) and blockssave (also an array) However, there are also functions included: var game = { blocksave: function() { blockssave = blocks; blo ...

Winston prefers JSON over nicely formatted strings for its output

I have implemented a basic Winston logger within my application using the following code snippet: function Logger(success, msg) { let now = new Date().toUTCString(); let logger = new (winston.Logger)({ transports: [ new (winsto ...

unable to dynamically refresh the display as the data is being updated

I have created a script in Python to loop through a set of files on a server, construct JSON data, and save it as a separate file. The script is working well so far. However, the number of files in the directory will be changing throughout the day. I am ru ...

How to align two <select> elements side by side using Bootstrap

The issue I am encountering is that these two select elements within the same control-group are being displayed vertically when I want them to be displayed horizontally. I attempted using inline-block in CSS, but there are other <div> elements with ...

Displaying tab content in AngularJS from a dynamic array

I am currently working on my very first Angular SPA project. Within a form, I have implemented three tabs and would like each tab to display its content only when selected. The contents of the tabs are stored in an array within the controller. I have spent ...

What is the best way to send a POST request with parameters to a PHP backend using AJAX?

This is an updated version of a previous question that was identified as a duplicate (How can I send an AJAX POST request to PHP with parameters?) I am currently sending an AJAX request to a PHP backend. Here are the JavaScript functions used to make and ...

A guide to JavaScript: Fetching and Parsing JSON Data from an API

Hey there! I've been working on using this code snippet in my defult.js file to call an API, but I'm having trouble figuring out how to read the output. It always seems to end up in the last else part. function fetchDataDist(APPID, flag, call ...

What is the process for transferring a JSON data object to the server with JavaScript XMLHttpRequest?

When I attempt to send an XMLHttpRequest to a PHP server, I am encountering difficulties in getting the $_POST or $_REQUEST object to be filled with the data I am sending using JavaScript: var r = new XMLHttpRequest; r.open("POST", "http://url.com", true ...

The search functionality in react-native-google-places-autocomplete seems to be experiencing issues as it is not displaying

I am currently working on a React Native component that incorporates a Google search feature for locations. To achieve this, I have utilized the Google Places API in hopes of enabling autocomplete functionality when users begin typing a city or address. I ...

Forward after asynchronous JavaScript and XML (AJAX)

Currently, I am working on an MVC project where I need to achieve the following: The scenario involves sending an ajax request from a JS script and then redirecting to a page along with a model once the request is processed. I attempted to send a form as ...

What is the best way to extract an object by its specific id using json-server?

I am attempting to retrieve an object by its id using json-server. If I only return a single variable (one JSON) in the module.exports of the database file, everything works fine. However, if I try to return an object with multiple variables, I encounter a ...

Exploring Scope Inheritance in AngularJS

Within the parent controller scope, I have initialized selectedItem as 'x'. Subsequently, in the child scope, selectedItem is declared using ngModel: <div ng-app> <div ng-controller="CtrlA"> <div ng-controller="CtrlB"> ...

Ways to implement functional component in ReactJs

I am currently working with Reactjs and utilizing the Nextjs framework. In my project, I am attempting to retrieve data from a database using Nextjs. However, I am encountering an error that states "TypeError: Cannot read property 'id' of undefin ...

Adjust the size of iCheck jQuery radio buttons

I have implemented the iCheck Plugin for radio buttons in Angular Directive, but I am facing an issue with resizing the radio button to a smaller size. Does anyone have any suggestions or solutions for this? ...

What is the best way to position a static element next to a Vue draggable list?

I'm currently working on implementing a feature to display a list of draggable elements using vue-draggable. These elements are occasionally separated by a fixed element at specified position(s). My approach so far has involved creating a separate el ...

Sending JSON data results

I received this JSON response: {"data":[{"series":{"id":"15404","series_code":"TOS","publisher_id":"280","series_short_name":"Tales of Suspense","start_year":"1959","end_year":"1968","published":"1959-1968","type_id":"1","no_issues":"99","published_ ...

Unable to load the .js file within the Angular module

I am facing an issue with my Angular sidebar component that is trying to load a local script called sidebar.js. I have the following code in src\app\sidebar\sidebar.component.ts: ngAfterViewInit(): void { const s = document.createEleme ...

What is the best way to eliminate a specific character from the key of an array of objects using JavaScript?

My JavaScript object looks like this: result = [ {"Account_ID__r.Name":"Yahoo Inc Taiwan","Contact_ID__r.Email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="42283427302c2d2e2602362a27313 ...

Firestore - Using arrayUnion() to Add Arrays

Is there a way to correctly pass an array to the firebase firestore arrayUnion() function? I encountered an issue while attempting to pass an array and received the following error message: Error Error: 3 INVALID_ARGUMENT: Cannot convert an array value ...