Chaining Promise Rejections in AngularJS

Creating chained promises is a task I need to tackle:

var deferred = $q.defer();
$timeout(function() {
    deferred.reject({result: 'errror'});
}, 3000);
deferred.promise.then(angular.noop, function errorHandler(result) {
    //additional actions
    return result;
}).then(function successCallback(result) {
    console.log('I'm stuck here');
    return result;
}, function errorCallback(result) {
   $scope.result= result;
   return result;
});

Adding an errorCallback in the first then results in the resolution of the second then, triggering its successCallback. However, if the errorHandler is removed, the second promise will be rejected.

As per Angular JS documentation, the sole way to propagate rejection is by returning $q.reject();. This approach may seem unclear, particularly since the injection of the $q service is necessary even when unnecessary;

Another option involves throwing an exception within the errorHandler, but this action logs the exception trace to the console, posing drawbacks.

Is there an alternative method to achieve this clarity? What reasoning stands behind it? Additionally, how can the current behavior prove beneficial in certain scenarios?

Answer №1

What is the purpose behind this action? When does this behavior come in handy?

This approach can be beneficial when handling errors and attempting to resolve promises within an errorHandler function.

var retryAttempts = 0;

function performTask()
{
    return $http.post('url')
        .then(function(response){
            // Check if the data returned contains a success property
            if(response.data.success)
                // Extract data from the response and potentially perform other operations
                return response.data;
            else
                // Reject with an error message
                return $q.reject('an error occurred');
        })
        .catch(function(reason){
            if(retryAttempts++ < 3)
                // An error occurred, attempt to recover and try again
                return performTask();
            else
                // Unable to recover after multiple retries, reject the promise
                return $q.reject(reason);
        });
}


performTask().then(console.log, console.error);

Answer №2

Arriving late to the gathering, but now that I'm here;

I personally opt for utilizing the $http error feature for its built-in error management, instead of indicating success with a 200 status and then conveying an error in the response.

Displaying 400 or 500 errors in the console is not problematic; if you are troubleshooting, you will see them, otherwise they remain unseen.

angular.module('workModule', [])

// work provider manages all API requests for work data
.service('workProvider', ['$http', '$q', function($http, $q) {

    var endpoint = '/api/v1/work/';

    this.Get = function(){
        // return the promise and utilize 404, 500, etc. for server errors
        return $http.get(endpoint);
    };

}])

.controller('workController', ['workProvider', function('workProvider'){

    workProvider.Get().then(
        function(response){ // successful request
            console.log(response.data);
        },
        function(response){ // error in request
             console.log(response.data);           
        }
    )

}])

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

Searching in real-time with ajax in CodeIgniter framework is a seamless and efficient process

I'm a beginner in CodeIgniter and eager to learn. Currently, I'm facing an issue where the data is not being populated on the search page. In the model: function fetch_data($query) { $this->db->select('*'); $this-> ...

Combining NodeJS with PHP: A Seamless Integration

They say NodeJS is perfect for creating real-time chat applications and I'm eager to add a chat feature to my website. Right now, I have the design ready and need to work on the back-end code. However, when I use socket.io + express, things don' ...

BlendModeGlobal operations

Experimenting with the globalCompositeOperation property in a loop by passing different strings (source-atop, source-over, etc.) to the same 2D context, I observed that Firefox only allowed me to draw a few shapes while Opera only displayed the last one. ...

When working with Visual Studio and a shared TypeScript library, you may encounter the error message TS6059 stating that the file is not under the 'rootDir'. The 'rootDir' is expected to contain all source files

In our current setup with Visual Studio 2017, we are working on two separate web projects that need to share some React components built with TypeScript. In addition, there are common JavaScript and CSS files that need to be shared. To achieve this, we hav ...

What is the syntax for linking to a different file in the frontmatter of a markdown file?

Currently, I am in the process of setting up Astro's Content Collections. One particular task I would like to achieve is referencing a specific author from my `authorCollection` within an article. In attempting to accomplish this, I considered utiliz ...

Is it possible to nest a React component within a state?

Is it permissible to use any of the three options below, but I can't find recent official information regarding this? constructor(props) { this.state = { item: <SomeItem />, item1: () => <SomeItem />, item2: Some ...

Validating the similarity of classes with JQuery

Currently, I am working on creating a quiz game using HTML, CSS, JQuery, and potentially JavaScript. I am looking to implement an if statement to check if a dropped element is placed in the correct div (city). My approach involves utilizing classes to comp ...

Angular encountered a 403 error while making an HTTP POST request

After successfully implementing angularJS validation in my form on localhost, I encountered a 403 Error (Forbidden) on line 72 of my angular.min.js file when trying to upload the code to my web server. I have tried numerous solutions but remain stuck on t ...

React.js - Add a new row div when reaching a limit of X items to keep the layout

Currently in the process of learning React.js. Here is the code snippet I am working with: const items = Object .keys(this.state.items) .map(key => <Item key={key} details={this.state.items[key]} />) ; return ( <div className ...

Loading a 3D model dynamically in three.js from a local file

Attempting to upload a 3D model from a local file during runtime is resulting in a CORS error message. While utilizing http-server for uploading predetermined models at the beginning works fine, the issue arises when trying to upload random objects from lo ...

Spontaneous Link with JQuery and Colorbox

Just to clarify, I have no programming experience so please explain everything in simple terms. I am currently using a .js script within SharePoint and it's working perfectly! <!DOCTYPE html> <html> <head> <meta charset= ...

Having trouble running the server in Node.js

When working with Node.Js, I encountered a specific issue My progress stopped at 6:16 when the instructions mentioned running "node server.js" to open 127.0.0.1:3000, but instead, an error occurred. https://i.sstatic.net/6esE5.png Upon checking my brows ...

An error has occurred: Expected a string as the element type in React when attempting to update the state

I encountered an issue while trying to update the state after fetching data. Error: Element type is invalid - expected a string (for built-in components) or a class/function (for composite components), but received: undefined. This could be due to forgett ...

Using three.js to establish an Image for Particle

I am looking to make some changes to this demo: Instead of having colored particles, I want to assign an image to each one. Should I use a cube for this purpose? Or is there a way to use an image with Vector3? Here is the code for the example: i ...

Looking to construct dynamic checkboxes in Angular by parsing a JSON object retrieved through AJAX

I have a JSON document structured like the example below, and I am looking to generate checkboxes dynamically using Angular. let data = { "Name":[ { "tagId":4489,"name":"Name","label":"Employee Name" } ], "Service":[ { "tagId": ...

Strange JSON.parse quirk observed in Node.js when dealing with double backslashes

My coworker encountered an issue while trying to parse a JSON string from another system, leading to unexpected behavior. To illustrate the problem, I have provided a simple code snippet below: // This code is designed for node versions 8 and above con ...

One clever AngularJS hack

Can anyone help me figure out how to call a function in a controller specifically for the first 'li' element in a 'ul' that is using ng-repeat? For example, I have a function in my controller: var init = function () { var a = this; ...

Unable to write or upload error in a Node Express application

My GET and POST APIs are functioning properly, however, my app.put is not working as expected. https://i.sstatic.net/Oc0QT.png Upon sending a PUT request to localhost:3001/contacts/1 using Postman, I am unable to see the console.log output: https://i.ss ...

"PHP Dilemma: Navigating the Ajax Button Press Situation

I've been attempting to create a button that triggers a PHP script on a webpage and updates only a specific div tag, but so far I haven't had any success. Removing the $ajax section of the script allows my buttons to change states, but as soon as ...

(NodeJS + Socket IO Issue) NodeJS is sending duplicate data when the page is refreshed, causing an improper response

Each time I refresh a page, NodeJS seems to be repetitively writing data on the socket. Interestingly, the number of writes increases with each page refresh but then stabilizes at three after several refreshes. I urge you to inspect the console output whi ...