Successive promises of catches

Here is a situation that I am dealing with:

controller.ts

methodA(): void {
    myServive.someMethod()
    .then( () => console.log("then") )
    .catch( e => {
        console.log("catch");
    });
}

service.ts

someMethod(): ng:IPromise<void> {

    const deferred = this.$q.defer<void>();

    return this.OtherService.otherMethod()
    .catch ( e => {
        deferred.reject(reason);
    }
}

otherservice.ts

otherMethod(): ng.IPromise<any> {
    return this.HttpService.get(url);
}

Test:

  • The otherMethod (otherService.ts) is encountering an error from the HttpService.
  • The catch in someMethod (service.ts) is being executed.

Why, in the controller.ts, is the then block being executed?

Answer №1

The catch block is executed if a preceding then (or catch) encounters an error. If no errors occur, the code will proceed to the next then statement.

Consider the following code snippet:

methodA(): void {
    myServive.someMethod()
    .then( () => console.log("then") )
    .catch( e => {
        console.log("catch"); // No errors thrown, so code execution continues in the next then
    });
}

You can intentionally throw an error within the catch block to trigger the subsequent catch block:

methodA(): void {
    myServive.someMethod()
    .then( () => console.log("then") )
    .catch( e => {
        console.log("catch");
        throw new Error(e) // An error occurred! The code will move on to the next catch block
    });
}

Answer №2

Why is the then block in controller.ts being executed?

The reason for this is that you caught the error and returned undefined in service.ts

If you do not intend to handle any errors in service.ts, it may be best to remove the catch/defer entirely from there.

Alternatively, if you want the catch to be handled in the controller, you can simplify service.ts like so:

// service.ts
someMethod(): ng:IPromise<void> {
    return this.OtherService.otherMethod()
}

If you wish to handle the catch both in service.ts AND in the controller, you can rethrow the error (or a new one) as shown below:

// service.ts
someMethod(): ng:IPromise<void> {

    const deferred = this.$q.defer<void>();

    return this.OtherService.otherMethod()
    .catch ( e => {
        // you can either do:
        // throw e
        // which rethrows the same error (similar to not having a catch at all)
        // or you can handle the error and throw a new one like:
        //
        // ...some error handling code
        // throw new Error('my new error');
    });
}

Regardless of your choice, a deferred is not necessary.

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

Animate the jQuery: Move the image up and down inside a smaller height container with hidden overflow

Check out the fiddle to see the animation in action! The image is programmed to ascend until its bottom aligns with the bottom of the div, and then descend until its top aligns with the top edge of its parent div, revealing the image in the process. ...

Utilize the functionality of the acuityscheduling API to streamline your

I've experimented with various methods but haven't had any success. Hopefully, you guys can share some insight. I'm utilizing acuityscheduling's API to fetch appointments. According to their documentation, the process should look someth ...

What counterpart in JavaScript resembles the .NET Standard Class Library?

As someone transitioning from a background in .NET to learning Vue.js, I'm curious about the best way to create classes that handle business logic for me. Specifically, I want to be able to fetch information from an API, format it as needed and easily ...

How can I apply concatMap in Angular?

Can you please guide me on how to effectively utilize concatMap with getPrices() and getDetails()? export class HistoricalPricesComponent implements OnInit, OnDestroy { private unsubscribe$ = new Subject < void > (); infoTitle ...

The absence of a query function in Select2 and Angular

I have integrated Select2 using its angular interface for a select form, here is my code: <select ui-select2 ng-model='thing' data-placeholder='Options' id='form1> <option value=''></Option> <opt ...

I encounter internal server errors when trying to upload images in React

Attempting to send a post request with an image, but encountering errors without understanding why. const [image, setImage] = useState([]); const handleImage = (event) => { setImage(...Array(event.target.files[0])) } const handleSubmit ...

What is the process for creating a custom Vue 3 element with incorporating styles for child components?

After experimenting with Vue's defineCustomElement() to develop a custom element, I encountered an issue where the child component styles were not being included in the shadow root for some unknown reason. To address this problem, I took a different ...

Progress of file uploads on the client side using Vue JS

I'm facing a challenge in creating a loading bar that shows the progress when a file is selected for upload in a form. Most of the examples I come across online demonstrate the loading bar after hitting an 'upload' button, but in my case, I ...

When using the `coffee-util` library, an issue may arise if the `require('./module')` function ends

When I develop using CoffeeScript 1.6.3, I simply run my application with coffee myapp. I also use coffee -c . to check the resulting .js files. However, when I try running coffee myapp again, the coffee utility for require(./module) uses .js files inste ...

Ways to troubleshoot setTimeout functioning during HTTP requests?

Utilizing Socket IO in my client app, I have implemented a feature to check for unread events. The process involves making a request to the backend, which then sets a 5-second timeout before checking for any new events and sending them back. // client soc ...

Retrieve the student ID from the URL parameters and display all records with the matching ID

I am trying to display all rows with the same id using $_GET['student_id'], but I am encountering an error with Datatables. Here is my code. When I get the id from the URL, for example: example.com/example.php?=2222 All rows with the id 2222 wil ...

The gear icon in the video player is not showing up when I try to change the

I am currently trying to implement a feature that allows users to select the quality of the video. I am using videojs along with the videojs-quality-selector plugin, but even though the video runs successfully, the option to choose the quality is not appea ...

What causes the list to be empty at first when using the "!" (not) in an AngularJS filter?

<p><input type="text" ng-model="test"></p> <ul> <li ng-repeat="x in names | filter:'!'+test"> {{ x }} </li> </ul> Is there a way to first show all items in the list and then progressively excl ...

Organizing seating arrangements for a concert hall performance

My goal is to develop a custom concert seat booking system using HTML, CSS, and JavaScript. For example, if the concert venue has 10 rows with 20 seats in each row, I could organize them like this: const rows = [ { name: 'A', seats: [1, 2, 3, ...

I'm curious, what should the Procfile look like for a node and Angular 2 application?

I am working on deploying my Angular 2 application to Heroku. I have successfully used a Procfile for my Node.js application in the past, where I included the following code: node serverName.js However, I am now facing confusion regarding what should be ...

Is there a way to determine if a value exists within an array of objects?

Is it possible to determine if a specific value is present in an array of objects? I've tried a method, but it always returns false. What would be the most effective way to solve this issue? My approach: var dog_database = [ {"dog_name": "Joey" ...

The ReactJS Ajax request returns a successful status code of 200 and retrieves the data, however, an error message

I have the following code snippet to fetch data from a backend API. When I paste the link into my browser's address bar, the API returns a result of '["2016-03-31T00:00:00"]'. However, when I use this AJAX call in my code, I receive a status ...

Unexpected token error occurs when using map-spread operator in vue-test-utils combined with jest

I recently set up testing for my Vue project by following the instructions provided in this helpful guide here Upon completion of the guide, I proceeded to create a test for one of my components. However, when I ran jest, I encountered the following error ...

The angular.copy() function cannot be used within angular brackets {{}}

Within my controller, I am utilizing the "as vm" syntax. To duplicate one data structure into a temporary one, I am employing angular.copy(). angular.copy(vm.data, vm.tempData = []) Yet, I have a desire to transfer this code to the template view so that ...

Execute a function upon the invocation of a different function

I am exploring how to trigger a function when another function is executed. While addEventListener is typically used for events like "click" or "mouseover", I am looking to detect when a function is called. For instance: Function 1 is invoked, an ...