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

Transforming complex mathematical equations into executable code using the node.js platform

Looking to implement a mathematical formula found at the following link: https://en.wikipedia.org/wiki/Necklace_(combinatorics)#Number_of_bracelets into node.js for calculating the total number of distinct ring sequences that can be created with n length ...

How can we implement the MUI snackbar to only show when a successful login occurs in ReactJS?

How can I display the material-ui snackbar in ReactJS only upon successful login? What approaches can be used to achieve this in ReactJS? ...

MVC3: Easily browse through tables by accessing details directly from the details view, eliminating the need to click on

I am currently working on an Index view where a table displays a list of items, each with a link to show its details in another partialview loaded through Ajax. Users have expressed interest in being able to easily navigate between "Next Item" and "Previo ...

Refreshing web pages using AJAX

I currently have an application that includes a search feature where users can look up items in the database. The search functionality is working well with AJAX, but I'm now looking to incorporate this AJAX functionality into my pagination system. Spe ...

Issues with Internet Explorer's scaling functionality are preventing it from operating correctly

I've utilized d3 to create a map. Its width is dynamically set based on the parent div's (with the id "map") width, and its height is calculated with a ratio of 5/9 in relation to the width. The viewBox attribute has been defined as "0 0 width he ...

What is the process for adding parameters to a Fetch GET request?

I have developed a basic Flask jsonify function that returns a JSON Object, although I am not certain if it qualifies as an API. @app.route('/searchData/<int:id>',methods=["GET"]) def searchData(id): return jsonify(searchData(id)) Curr ...

Retrieve both the key and corresponding value from a JSON object

I am attempting to extract the key and value pairs from a JSON dataset. $.get(url, function (data) { console.log(data); if (data.Body != null) { console.log(data.Body); } }); These are my current logs: { $id: "1", Exceptions ...

Mocking a React component with Jest's MockImplementation

Currently, I am in the process of testing a react component that renders another component. This secondary component makes an API call to fetch data which is then displayed on the screen. My goal is to understand how I can mock this particular component&ap ...

Twice the data fetching through ajax on popup is observed using php mysql

I've been struggling for the past two hours. Attempted : location.reload(); reset form Tried many features, but after closing my popup and reopening it or opening another ID, the previous ID data is still visible. This happens continuously for all ...

Adding content to the parent element immediately after it is generated using jQuery

Is there a way to trigger $(e).append() as soon as the element e is created without using setTimeout()? I find that method inefficient. Are there any DOM events that can detect changes in a subtree of a DOM element? Usually, I would just add the code to t ...

JavaScript code for iframe auto resizing is not functioning properly on Firefox browser

I have implemented a script to automatically resize the height and width of an iframe based on its content. <script language="JavaScript"> function autoResize(id){ var newheight; var newwidth; if(document.getElementById){ newh ...

Proceed to the section with modal

My goal is to create a modal with 4 sections, each loading its content dynamically using the .load() function to the container on the right side. The challenge I'm facing is that I have a footer menu that triggers the modal to open, and I need it to ...

Does the Karma Tast Runner function on node js version 0.12.0?

I'm experiencing an issue where I have Node.js v0.12.0 installed with Karma on my OS X Yosemite, but when I try to run my test task using Gulp, it just hangs as shown in the picture. It seems like PhantomJS is not starting. Interestingly, the same cod ...

When a user accesses a page, the UI-router shows the raw code in the UI-views

I am a newcomer to utilizing ui-router and I am facing challenges with managing routing and reloading some states. Any assistance would be greatly appreciated. An overview of my index.html <html ng-app="resApp"> <head></head> < ...

Unpacking the information in React

My goal is to destructure coinsData so I can access the id globally and iterate through the data elsewhere. However, I am facing an issue with TypeScript on exporting CoinProvider: Type '({ children }: { children?: ReactNode; }) => void' is no ...

Unable to modify the active property of the specified object as it is read-only

Presented here is the interface: export interface ProductCommand extends ProductDetailsCommand { } This is the ProductDetailsCommand interface: export interface ProductDetailsCommand { id: string; active: boolean; archive: boolean; title: ...

I am facing difficulties accessing external URLs in a webview within my Ionic Android application

Recently, I encountered an issue with my Ionic app where it opens an external URL in a webview. The app worked perfectly fine when tested on the iOS simulator, but when testing it on the Android simulator, it failed to function correctly. Upon checking the ...

What causes the d3 force layout to fail and what steps can be taken to resolve it?

While experimenting with a force layout, I noticed that when I drag an item aggressively, it sometimes causes everything to freeze. This raises the following questions: What is the reason behind this issue? Is there any way to detect this and restart th ...

Tips for saving a value within a jQuery function for future use in a different function

I have a situation where I receive a value from a jQuery function that I need to pass to another function. How can I achieve this? jQuery.getJSON(url+"&startDate="+startDate+"&endDate="+endDate+"&jobId="+jobId+"&type="+type, function(data) ...

Troubleshooting V-model errors within VueJS components

Just dipping into VueJS and trying out a chat feature from a tutorial. I noticed the tutorial uses v-model in a component, but when I replicate it, the component doesn't display on the screen and the console throws a "text is not defined" error. Strug ...