Linking promises together ensures that they always resolve with a result

My understanding of how to chain promises is still not completely solid. What I am trying to achieve is as follows:

I have a promise that can either resolve or reject. The following code checks for this and continues if the promise resolves, or stops if it rejects. However, I simply want to run this promise without worrying about its outcome.

The way I used to do it was:

function a(){
    return Service.doSomething();
}

So I wrapped it in another promise and here's the result:

function a(){
    var q = $q.defer();
    Service.doSomething(); // I don't even need to handle whatever the outcome is
    q.resolve();
    return q.promise;
}

(Yes, this is from an Angular project)

Although this works, it doesn't look very elegant. Is there a better or cleaner way to write this?

Update: I understand that this behavior might seem strange, so let me explain a bit more.

This example pertains to Angular routes and my custom middleware for authentication handling.

I've created three special "route" handlers:

  • customRoute
  • onlyGuest
  • onlyUser

Instead of writing

$routeProvider.route({});

I write (for example)

$routeProvider.customRoute({});

Each of these special route handlers extends the resolve attribute of the route with authentication logic.

For instance, I can do the following:

$rootScope.$on('$routeChangeError',function(e, current, previous, rejection){
        // Only for logged in users
        if (rejection && rejection.needsAuthentication){
            $rootScope.refUrl = $location.path();
            $location.path('/user/login');
        }

        // Only for non-logged in users
        if (rejection && rejection.isOnlyGuest){
            $rootScope.refUrl = $location.path();
            $location.path('/dashboard');
        }
    });

The functions onlyGuest and onlyUser are self-explanatory, but I also have customRoute() which essentially runs the authentication method to retrieve user info when a user accesses the app directly through this URL, whether they are a guest or logged in.

The issue arises when the authentication method throws a reject(). This triggers the route change error. Therefore, for customRoute(), I need to run the authentication process without triggering the changeError – always resolving as true even if the authentication()'s promise rejects.

I hope this clarifies things rather than confusing them further...

Answer №1

In order to accomplish the customRoute() functionality, it's necessary to execute the authentication process without transitioning to changeError - always ensuring a positive outcome even if the authentication() promise is rejected.

It appears that utilizing catch can help in disregarding rejections:

function customRoute() {
    return authentication().catch(function(changeError) {
        // disregard error
        return true;
    });
}

Answer №2

function b() {
    return Service.performTask().then(angular.noop, angular.noop);
}

What occurs? When you provide a function as the error callback to then() and that function does not return $q.reject(...), the promise created by then() is actually resolved instead of being rejected.

Take a look at this small demo: http://jsfiddle.net/u6kzo1o0/

Keep in mind though that your intended outcome may be unconventional, as mentioned by @New Dev's comment.

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

Sending the slider value from a website to a program when the slider is adjusted

I have been experimenting with programming an ESP32 to regulate the LED brightness using a slider. I've pieced together some information from tutorials found on and Currently, I've achieved the ESP32 connecting to my network, displaying the sli ...

PHP and JavaScript: Understanding Variables

I currently have a View containing an Associative Array filled with information on accidents. Users will have the ability to click on a Country. Once clicked, I want to display accident-related data for that specific country. This data is pulled from PHP ...

Implementing click events to control GSAP animations in Next.js

I'm having trouble figuring out how to pause/start an animation using GSAP in Nextjs. Specifically, I can't seem to work with a tl.current outside the useEffect hook within this component. My goal is that when I click on the first .imgWrapper ele ...

Issue encountered when toggling flip switch in Jquery Mobile

I am trying to create a calculator for my app using Jquery Mobile, but I am facing an issue with the flip toggle switch. Here is my script: <script type="text/javascript"> function dosis() { $peso = $('#peso').get(0).value $dosis = ...

Display complete information of the selected list in a modal window by clicking on it in PHP Yii

I recently started working with the Yii framework and encountered a challenge when trying to pass data from a list to a modal using AJAX. The modal is located within the same view as the list. Here's a snippet of my code: This is my view: <div id ...

Unable to retrieve private field using a public getter method through a proxy

When retrieving data from a VueX Module using a Getter, the Object is enclosed within a Proxy that triggers the following error: TypeError: attempted to get private field on non-instance when attempting to access a private property with a public getter. ...

Problem encountered when Next.js and CSRF token interact on the server

I've integrated the next-csrf library (https://github.com/j0lv3r4/next-csrf) into my next.js app to safeguard api routes. Despite following the documentation, I'm encountering a 500 error with the following message: {"message":"Si ...

What is the reason for HereMap factoring in stopOver time when calculating travel time for the destination waypoint?

I am currently working on a request using the HereMap Calculate Route API. Waypoint 0 does not have any stopOver time, but waypoints 1 and 2 do have stopOver times. Below is an example of the request: https://route.ls.hereapi.com/routing/7.2/calculateroute ...

The @Input() property within an Angular component is producing an empty array as its result

I have a calendar component that has a data property marked as @Input(): import { Component, OnInit, Input, OnChanges, SimpleChanges } from '@angular/core'; @Component({ selector: 'app-calendar', templateUrl: './calendar.comp ...

Trouble arises when trying to load angular ui-bootstrap using require.js unless I change the name to ui.bootstrap

Code Overview: main.js: require.config({ paths: { 'uiBootstrap': '../lib/bootstrap/angular-bootstrap/ui-bootstrap-tpls.min' }, shim: {***}, priority: ['angular'], deps: ...

Guide to retrieving the previous URL in Angular 2 using Observables

Can someone help me retrieve my previous URL? Below is the code snippet I am working with: prev2() { Promise.resolve(this.router.events.filter(event => event instanceof NavigationEnd)). then(function(v){ console.log('Previous ' ...

What is the reason behind only seeing empty brackets [] when Array.prototype is displayed in

When looking at String.prototype, Object.prototype, and Boolean.prototype, we see that they all have a similar structure where the object {} is displayed. However, when it comes to Array.prototype, instead of displaying Array [], it outputs []. Why does ...

Utilizing Fullcalendar Qtip to display information on mouseover rather than utilizing the eventRender

I have a challenge with integrating Qtip to the eventMousever event instead of the eventRender event in fullcalendar. The main reason for this adjustment is due to the server hosting the data being located in another country, resulting in significant late ...

Using jQuery, selectively reveal and conceal multiple tbody groups by first concealing them, then revealing them based on

My goal is to initially display only the first tbody on page load, followed by showing the remaining tbody sections based on a selection in a dropdown using jQuery. Please see below for a snippet of the code. //custom JS to add $("#choice").change(func ...

Converting an array into a JavaScript Date object

I am currently working with an array of dates and looping through each element. The elements within the array are not date objects but rather strings, I believe. When I print each of the elements to the console, they appear as follows: 2015,09,19 2015,09, ...

After the request.send() function is called, the request is not properly submitted and the page automatically redirects

I'm currently working on a basic ajax comment form that includes a textarea and a yes/no radio button. If the user selects 'yes', their comments are posted and then they are redirected to a new page. If the user selects 'no', th ...

Execute identical task using a for loop in JavaScript

Here is a sample code snippet: var seats = [] for (a = 0; a <= seatsNumFront; a++) { seats.push(new Seat((a * xPad) + 300, 60, 30, 30, id++, "A", a, "#998515")) } for (b = 0; b <= seatsNumFront; b++) { seats.push(new Se ...

What is the best way to invoke functions with input of type 'number'?

As someone new to HTML, I have an input field with type=number: <input type="number" min="1" value="1" id="amount-input" (click)="chooseStanding(standingspot.priceCategory)"> When the (click) event i ...

What is the process for storing user-provided document names in Firestore database entries?

I'm encountering an issue with my API while trying to utilize Firestore for inputting data for login and registration via the API. The problem arises when attempting to add a document entry in the database with the user's input email during regis ...

The dropdown menu is extending outside the header in a right-to-left (RTL) direction

I have implemented the jQuery code below to prevent the dropdown from extending beyond the header area. It works perfectly in the normal LTR version. However, I need a solution for the RTL version. How can I achieve this? jQuery $('.primary-menu .dr ...