Execute AngularJS $q.all, regardless of any errors that may occur

Is there a way to ensure $q.all is triggered even if the promises return errors?

I'm working on a project where I need to make multiple $http.post requests, sending user-inputted values from text fields. The backend (Django REST framework) has a value checker that returns a 400 status if the posted value doesn't match the expected format. This causes $q.all not to trigger, leading to various errors in my application.

//Code snippet for handling $http post requests
for(var i = 0; i < num_requests; i++){
    var writeRes = $http({
        method: 'POST',
        url: '/' + api_prefix + '/values/',
        data: out_data,
        headers: { 'Content-Type': 'application/json','X-CSRFToken': $scope.valueForm.csrf_token,'Accept': 'application/json;data=verbose' }
    });

    saved.push(writeRes);

    writeRes.success(function(data, status, headers, config){
        $scope.scope.param_values.push(data.id);
    });
    error(function(status){
        //Handle error here
    });
}

$q.all(saved).then(function() {
    //Perform other tasks once all requests are completed 
}

The correct values are being posted, but if an error occurs, the processing after $q.all doesn't get executed, causing issues upon page refresh.

Is there a way to make sure that $q.all runs regardless of any errors?

I apologize if my questions are unclear, as I am relatively new to frontend development and struggling with this project.

Answer №1

Learn how the documentation explains the $q.reject() method and illustrates how to catch rejection callbacks and successfully recover from them.

In this scenario, simply by returning a new value within the rejection function, $q will interpret the promise as resolved:

writeRes.then(function(data, status, headers, config){
    $scope.scope.param_values.push(data.id);
    //an array of IDs that pertain to the REST framework.
}, function(error){
    // manage the error situation and successfully recover
    return true;
});

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

Adding items to an array within a jQuery each loop and performing a jQuery ajax request

I am trying to loop through an array, push the results into a JavaScript array, and then access the data outside of each loop and AJAX call. Can anyone explain how to do this? This is what I have attempted: var ides = ["2254365", "2255017", "2254288", ...

PhoneGap and jQuery prove ineffective in fetching json results from Twitter

I've been working on a project to fetch the most recent 50 tweets with a specific hash tag. The project is built for mobile devices using PhoneGap (0.9.6) and jQuery (1.6.1). Below is my code: function retrieveTweets(hash, numOfResults) { var uri ...

What is the approach of Angular 2 in managing attributes formatted in camelCase?

Recently, I've been dedicating my time to a personal project centered around web components. In this endeavor, I have been exploring the development of my own data binding library. Progress has been made in creating key functionalities akin to those f ...

What is the reason that the slick slider is unable to remove the class filter?

Having troubles with my slickUnfilter function, even though slickFilter is working perfectly? Here's a snippet of my HTML: <div class="slider-wrapper" id="wrapper"> <div class="post" id="post1"&g ...

"Using the power of jQuery to efficiently bind events to elements through associative

I am attempting to link the same action to 3 checkboxes, with a different outcome for each: var checkboxes = { 'option1' : 'result1', 'option2' : 'result2', 'option3' : 'result3', }; ...

Using focusout and clicking buttons do not effectively interact with child elements

I have a series of div elements, each containing a button. When I click on a button, text is displayed, and when I click away, the information hides with a focus-out function. If I have one button open and then want to click on another parent button, it wo ...

Adding a custom class to a select2 dropdown: How can it be done?

I have customized select2 using CSS with its general classes and IDs. Currently, I am attempting to customize a specific class that will be assigned to select2 and then applied in the CSS. The problem lies not within the select itself, but within its dro ...

Unpacking and reassigning variables in Vue.js 3 using TypeScript

I am working with a component that has input parameters, and I am experimenting with using destructuring assignment on the properties object to reassign variables with different names: <script setup lang="ts"> const { modelValue: isSelected ...

ng-table Filtering with dropdown selection

Hello, I am currently working on creating a Ng-table with a select dropdown menu for filtering the results. Here is where I am at so far. 1) How can I remove one of the pagination options that appear after applying the filter? I only want to keep one pagi ...

What is the reason behind observing numerous post requests in the Firebug console after submitting a form through Ajax in jQuery?

I have integrated the jquery Form plugin for form submission and everything seems to be functioning properly. However, upon turning on the firebug console and clicking the submit button, I notice that there are 10 post requests being sent with the same da ...

Refresh meta tags in a Next.js/React app

In the process of optimizing a website for SEO, I am facing the challenge of updating the meta description's content dynamically without using any third-party libraries. While I have successfully implemented the functionality, it currently requires a ...

What is the best way to update object values only when changes occur, and leave the object unchanged if no changes

There is an object named ApiData1 containing key-value pairs, including color values within properties. The colors are updated based on the numberOfProjects value from ApiData2, with specific ranges dictating the color updates. This setup is functioning co ...

What is the best way to pass a prop into the <router-link>?

If I replace this {{ name }}, the result is "campaigns" Now, I want to use that in my link <router-link :to="'/' + '123' + '/' + item.id"> {{ item.name }}</router-link> I attempted to substitute '1 ...

Exploring the implementation of Chain Map or Chain Filter within an Angular Http request that delivers a promise

I have a dataset in JSON format that I am working with, and I need to filter out specific key values using lodash. I want to reject multiple keys that I don't need. My initial approach is to either chain the map function and then use the reject funct ...

How can I remove the outline when focusing with the mouse, but still retain it when focusing with the

Is there a way in JavaScript to detect if an element received focus from the keyboard or mouse? I only want the outline to show when it's via the keyboard, not the mouse. If this is possible, how can I override the browser's default outlining be ...

Listening to LayersControl.Overlay checkbox clicks in React-Leaflet: A guide

My goal is to dynamically render overlay controls and bind a click event listener to the checkbox of each control in React. However, I am unsure how to provide a React ref to LayersControl or an onClick handler to LayersControl.Overlay. Is there a more eff ...

Unable to showcase Angular model in an alternative view

I'm currently working on a sample application where I need to display my model in one view and allow editing in another. Here's the controller code I'm using: var app = angular.module('plunker', ['ngRoute']); app.contro ...

Tips for deactivating all JavaScript events on a webpage that has been loaded within an iframe

My website is equipped with various JS click/mouseover/mouseout/scroll events and incorporates several JS libraries to operate features such as carousels, bootstrap modal pop-ups, and more. I am looking to halt all events on a specific element. Although I ...

Creating a responsive design for mobile apps in Ionic using CSS

I need help with making my Ionic app responsive across all mobile devices. The design on the page was created using CSS, but it is not displaying properly on every device. How can I ensure that it adapts to different screen sizes? <template> <Io ...

Swap out a div identifier and reload the page without a full page refresh

I am interested in learning how to dynamically remove a div id upon button click and then add it back with another button click to load the associated CSS. The goal is for the page to refresh asynchronously to reflect these changes. So far, I have successf ...