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

Enhancing code with new Javascript functionality

Currently utilizing the WordPress Contact Form 7 plugin and in need of updating my existing JavaScript code to include an onclick function and data-img attribute for checkboxes. Due to the limitations of Contact Form 7 shortcode, adding attributes beyond i ...

Tips for including or excluding a series of comma-delimited values from an input

HTML <div class="wrap_temi"> <ul class="list-inline list-unstyled"> <li class="list-inline-item"> <input type="checkbox" value="amici" autocomplete="off"> Amici </li> <li class="lis ...

Bringing an AMD module into a Mocha test

I recently encountered an error while using Mocha to test code that was exported as an AMD module. When running the Mocha test, I received the following error message: ReferenceError: define is not defined at Object.<anonymous> (/home/malintha/proje ...

When combining Socket.io 1.0 with express 4.2, the outcome is a lack of socket connection

According to the title, I am attempting to integrate socket.io 1.0.4 with express 4.2, but all requests with "/?EIO" are resulting in a 404 error. Below are my file configurations: ./bin/www : #!/usr/bin/env node var debug = require('debug')(& ...

Zoom in and Zoom out functions in ngPdf with centered view

I have incorporated the pdf canvas to showcase PDFs on my AngularJS/Bootstrap application, and I must say, the preview feature is working exceptionally well. However, one thing that I would like to achieve is centering either my modal or the canvas itself ...

Tips for embedding a file within a text box in HTML and enabling users to make direct edits

I am currently working on a feature that allows users to open a .txt or .html file from their file explorer and paste the contents into a textarea for editing and saving purposes. My question is whether it's possible to read the file content and auto ...

Find the mean of two values entered by the user using JavaScript

I'm sorry for asking such a basic question, but I've been struggling to get this code to work for quite some time now. I'm ashamed to admit how long I've spent trying to figure it out and how many related StackOverflow questions I ...

The current registry configuration does not provide support for audit requests when running npm audit

I am facing an issue with one of my dependencies that is in the form of "protobufjs": "git+https://github.com/danieldanielecki/protobufjs-angularfire.git#master". I installed it using npm install --save https://github.com/danieldanielecki/protobufjs-angula ...

Ways to append each list item from one unordered list to the end of another based on their unique styles

I am in the process of making a website responsive and I am faced with the task of combining two different menus. In order to achieve this, I need to transfer all list items (li) from one unordered list (ul) to another. Provided below is a simplified vers ...

A JavaScript function to separate a URL and eliminate the final segment

http://www.google.com/site!#656126.72367 Is there a way to split and remove the part after the exclamation mark in this URL using JavaScript when the page is loaded? I am looking to achieve http://www.google.com/site ...

Preventing Duplicate Form Submissions in Rails 5 using jQuery

As a coding novice, I'm currently working on my Rails 5 app and implementing image cropping and uploading directly to AWS S3 from the client side using blueimp/jQuery-File-Upload. However, I have encountered an issue where multiple form submissions o ...

Karma testing shows quick results, but in reality, the performance is sluggish

If you'd like a visual explanation, check out this video (or see the gif below): The Karma progress reporter may indicate that the tests are taking milliseconds, but in reality, it's taking much longer... I mentioned this on Twitter and was adv ...

Incorporating JavaScript/JSON into your Ebay listings to seamlessly receive user-selected choices

There has been a trend among Ebay users to incorporate dynamic data fetching and sending from external sources in their listings. This could be for implementing a shipping calculator or offering different product variants through dropdown lists. You can c ...

Implementing custom validation in React to dynamically enable/disable buttons

I am working on a basic form that includes 3 input fields and one submit button. The submit button is initially disabled, and each input field has its own custom validation logic using regex. I am looking for a way to enable the button only when all the ...

Obtaining Google AAID Using a Mobile Browser (JavaScript)

I've been looking for information online without much success regarding this topic. I am interested in retrieving a user's Google Advertising ID (AAID) through my website when they visit using a mobile browser. I assume it could be done with som ...

What is the best way to automatically insert data into a database at regular intervals, while ensuring that users are unable to manipulate the timing through inspect

Is there a secure way to insert 1 point into the database every x seconds without allowing users to manipulate the interval time through inspect element? var time = 1; var interval = setInterval(function() { if (time != time + 1) { ...

Tips for extracting a value from a geojson response using a specific key

When analyzing the geojson response below, I am trying to access the following: Type and Segments To achieve this, I attempted the following: return data["type"] //does not work, error received return data["features"][0]["properties"]["segments"] ...

learning how to combine two json arrays of objects and showcase them in a react component

What is the best way to combine this data and present it in a table with a map using React? The text will be in the first column and the count in the second. const handleSubmit = async (event) => { event.preventDefault(); let URL1 = " ...

Why does Angular.js promise keep returning [Object object]?

Trying to fetch an object through a promise in the service, but facing issues with data transfer to the controller. Call from the controller: dataService.getSpanishOverviewByID(newItem, api) .then(getSpanishOverviewByIDSuccess) .catch(errorCallback); T ...

Is it possible to include two of these on a single page with unique variables? (Using JQuery)

I am looking to create two similar pages, each with different percentages. However, when I try modifying the JS or changing class/ID names, it keeps pulling data from the first SPAN element. http://jsfiddle.net/K62Ra/ <div class="container"> <di ...