What is the reason behind the success of chaining $q.when and $q.reject in Angular.js?

Why does this code not trigger the error callback when using $q in Angular.js:

 $q.when("test")
   .then($q.reject("error"))
   .then(
     function(v) {
       $scope.result = "Success: " + v;
     },
    function(e) {
       $scope.result = "Failure: " + e;
     }
   )

You can test it on a JSFiddle here: http://jsfiddle.net/c9tv6kz7/1/

Answer №1

According to the documentation

when(successCallback, errorCallback, notifyCallback) – irrespective of the timing of promise resolution or rejection, when triggers either the success or error callback as soon as the result is available. These callbacks receive a single argument: the result or reason for rejection. The notify callback can also be used to provide progress updates before resolution or rejection.

This function returns a new promise that is resolved or rejected based on the return value of the successCallback, errorCallback (unless it's a promise itself, in which case it resolves with the value from that promise through chaining). It also notifies using the return value of the notifyCallback. The promise cannot be resolved or rejected directly from the notifyCallback.

The key statement here is

This function returns a new promise that is resolved or rejected based on the return value of the successCallback, errorCallback

Every time you invoke when on $q.when, it generates a new promise. Even if the first promise was rejected, the second one wasn't. This is because the return values of the successCallback and errorCallback didn't reject it.

Answer №2

Simply put, the more straightforward explanation is:

$q.reject("error")

generates a fresh promise object that is triggered by the $q.when().then().

This will not function as expected. When you use $q.reject("error"), it yields an object with a then function attached to it.

Refer to the Methods section in the documentation:


promiseB = promiseA.then(function(result) {
// success: take action and resolve promiseB
//          with the original or a new result
return result;
}, function(reason) {
// error: try to handle the error and
//        resolve promiseB with newPromiseOrValue,
//        otherwise pass on the rejection to promiseB
if (canHandle(reason)) {
// manage the error and recover
return newPromiseOrValue;
}
return $q.reject(reason);
});

Observe how they utilize

then(function () { return $q.reject(reason); })
, which differs significantly from your initial approach.

Check out the updated example

Answer №3

When I follow this method, I successfully address an issue:

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', ['$scope', '$q', function($scope, $q) {
  $q.when("test")
    $q.reject('Failed!')
    .then(
      function(v) {
        $scope.result = "Success: " + v;
      },
      function(e) {
        $scope.result = "Failure: " + e;
      }
    )
}]);

http://jsfiddle.net/emporio/67db45f9/3/

If the $q.reject('Failed!') part is omitted, it will proceed to .then().

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

Tips for identifying and swapping values/parameters in a URL during redirect

To provide more clarity on my inquiry, I will outline the details below: There are three links: Link A, Link B, and Link C Link A: {c_val} Link B: {id} Link C: In the database, there is a value adgaf7g6adf6gadfg8a86fgs9f6g The main focus here is when ...

Preserve data across all pages using sessions

On my website, I have a pagination system where each page displays 10 data entries. Whenever a user clicks on the pagination buttons, it triggers a request to the database to fetch the corresponding records. Each data entry also includes a button that can ...

What is the best way to add data to my collection using the main.js file on the server side in a Meteor application

I am a beginner with Meteor and trying to customize the tutorial codes. I have a code that listens for packets on my server-side main.js. Now, I need to store the data printed on the console into my database collection. import { Meteor } from 'meteor/ ...

changing the core JavaScript of a keyboard plugin

To access the demo, click on this link: . You can find the main javascript file at https://raw.githubusercontent.com/Mottie/Keyboard/master/js/jquery.keyboard.js. Is there a way to switch the positions of the accept and cancel buttons? ...

Utilizing emotion with MUI v5 for dynamic theming

After upgrading MUI from v4 to v5, I'm facing some difficulties grasping the concept of theming with the various solutions available. I find it challenging to determine when to use MUI theming/styling components and when to opt for emotion ones. Whil ...

"Troubleshooting the issue of Angular's select binding causing a disruption

The Angular version being used is 1.4.7. Within the model in question, there are two objects: 'systems', which is an array, and 'selectedSystem'. The desired outcome is for 'selectedSystem' to reference one of the objects wit ...

Creating an object positioned to the right side of a div (div:right) is a matter of using CSS positioning properties

While we are familiar with pseudo-classes like :before and :after, have you ever wondered why there is no nav ul li a:left or :right? Do you think it's achievable? I'm open to using HTML5, CSS3, and JavaScript to make it happen. ...

Set up Node.js application to allow CORS for designated endpoint(s) exclusively

I am currently facing a dilemma with my Node application and how to handle cross-origin resource sharing. In the past, I have used a PHP proxy to bypass this issue when calling endpoints from JavaScript/AJAX. However, I am now looking to streamline the pro ...

Display data when clicking on Tailwind

I am currently displaying a sub menu on hover using Tailwind CSS. However, I am wondering how I can achieve the exact same functionality by triggering an onclick event instead of hovering over the menu. Here is a DEMO showcasing the current setup. CODE: ...

Ways to send user input to a function within a React component

I am currently working on implementing a simple feature where users can search posts by their tags. To achieve this, I have created the Feed.jsx component with the following code: "use client"; import { useState, useEffect } from "react&quo ...

Using `ng-class` strategically within a list of elements

Currently, I am working with a list of checkboxes and trying to apply a class conditionally using ng-class when the checkbox is clicked. However, the issue I am facing is that the class gets applied to all items in the list instead of just the specific one ...

Mastering AngularJS - Field Population with Blinking Placeholders

I understand that AngularJS fills in fields through their model. HTML is loaded first: <input type="text" data-ng-model="data.myValue" placeholder="example"> The JavaScript code comes next: $scope.data = {}; $scope.data.myValue = 'hello my v ...

If Gulp is running continuously, what output will I receive?

After reading a helpful post on StackOverflow about gulp tasks (viewable here), I came to the conclusion that it's not advisable to omit returning anything in a gulp task. For proper synchronization of asynchronous tasks, the caller should wait. Pres ...

Using Cypress for drag and drop functionality within shadow DOM

I encountered an issue in cypress with drag and drop functionality within the shadow dom. My attempt to perform a drag event is as follows: cy.get(".shadow-app>div>div:nth-child(1)", { includeShadowDom: true }).trigger("dragstart&q ...

Only perform the Rails ajax call once initially

I'm currently working on creating a drop down menu that contains a substantial amount of content, and I would like to use an ajax get call to load everything upon mouse enter. Here is my code written in coffeescript: class @SecondaryMenu construct ...

What is the best way to retrieve the latest state after applying useEffect to trigger an onChange event for an element?

I am encountering an issue with an input field in my component that requires an onChange event to update the state. Despite binding the onChange event on mounting the component, the state remains unchanged as the onChange event seems to have the initial st ...

Having trouble passing a token for authentication in Socket.IO v1.0.x?

I am currently following a tutorial on creating a token-based authentication system, which can be found here. I have implemented the following code: Code in app.html: var socket = io('', { query: "token=i271az2Z0PMjhd6w0rX019g0iS7c2q4R" }); ...

Tips for transferring a JavaScript variable to a Java servlet using the doPost method

I am working with an HTML table that contains dropdowns. When a user clicks on a dropdown, I store the column name and corresponding row (billdate) in a variable. Now, my goal is to pass this variable to my Java servlet's doPost method and then use it ...

What is the method for activating a button when a user inputs the correct email address or a 10-digit mobile number

How can I enable a button when the user enters a correct email or a 10-digit mobile number? Here is my code: https://stackblitz.com/edit/angular-p5knn6?file=src%2Findex.html <div class="login_div"> <form action=""> <input type="text" ...

Mongodb failing to recognize the concat function

I have a field within my collection that looks like this: uniqueId: 123 inTarefa: true exclude: "ab,cd," orderId: 987 I am attempting to update all of the values using a "FindOneAndUpdate" query like so: collection.findOneAndUpdate({ 'uniqu ...