What triggers the execution of the catch method while chaining HTTP promises?

In my Angular application, I have developed a custom loaderService that displays a loading spinner while the back-end processes requests. Below is the code snippet:

export class ComponentOne {
  constructor(loaderService: LoaderService, orderService: OrderService) {}
  ...
  ...
  method() {
    this.loaderService.display(true);
    this.orderService.firstRequest()
      // the misspelled word causes a 500 error
      .then((response) => this.orderService.methodWithWrongInput('misspelled_word'))
      // but it still executes the following then
      .then(() => this.method2())
      .catch(() => null)
      .then(() => this.loaderService.display(false));
  }
  ...
}

Even though I display the spinner before the request, I make sure to close it regardless of the success or failure of the request by using catch and a final then. While debugging, I noticed that despite the second request failing due to the misspelled word, method2() is still being invoked. Or is it really failing?

I am curious about how the catch method operates when chaining requests. I presumed that if a request fails, we would directly jump to the catch method, but I may be mistaken.

Edit: Upon further investigation, I discovered that my assumption about method2() being executed was incorrect. For more details, refer to T.J. Crowder's response.

Answer №1

Upon reflection, it became clear to me that despite the failure of the second request (due to the intentional misspelling), the function method2() is still being invoked...

I have a hunch that you might be misinterpreting what you're observing in the debugger, which can happen quite easily in this scenario.

In the given code snippet:

method() {
  this.loaderService.display(true);
  this.orderService.firstRequest()
    // the misspelled word causes a 500 error
    .then((response) => this.orderService.methodWithWrongInput('misspelled_word'))
    // but it still executes the following then
    .then(() => this.method2())
    .catch(() => null)
    .then(() => this.loaderService.display(false));
}

Here's a breakdown of events:

  1. this.loaderService.display(true);
    is executed
  2. this.orderService.firstRequest() runs and returns a promise
  3. .then((response) => this.orderService.methodWithWrongInput('misspelled_word'))
    is triggered—only setting up the next step in the Promise chain, not actually running the callback. It creates and returns a new promise.
  4. .then(() => this.method2()) is run—again, just setting up the upcoming step, not executing its callback. Another new promise is returned.
  5. .catch(() => null) is initiated—not running the callback, only setting up the catch block. This also results in a new promise being returned.
  6. .then(() => this.loaderService.display(false))
    is carried out—the same setup process as above, generating another new promise.

Subsequently, when the promise from firstRequest() resolves, the following occurs:

  1. (response) => this.orderService.methodWithWrongInput('misspelled_word')
    is called and produces a new promise

Afterwards, when this subsequent promise is rejected:

  1. () => null (within your catch handler) is executed, returning null, which leads to resolving the associated promise (essentially converting a rejection into a resolution)
  2. () => this.loaderService.display(false)
    is processed because the chain is now resolved (not rejected) at this point, thanks to the previous step #8

Therefore, in the debugger, you may notice that the execution cursor moves past the then call for method2 during the initial sequence (#4) where the chain is being orchestrated synchronously. However, this action simply adds the handler to the sequence. You won't witness the actual invocation of method2 since that callback isn't triggered when resolutions or rejections occur (such as in cases where methodWithWrongInput encounters a rejection).

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

The 'cookies' property is not found on the 'Request' type

Currently, I am attempting to access a cookie within a NestJS controller. I have been referencing the documentation found at https://docs.nestjs.com/techniques/cookies#use-with-express-default Below is my implementation: import { Controller, Get, Render, ...

After the assignment, TypeScript reordered the elements of the array

Dealing with an array of objects for use in a ngFor loop has presented a challenge. The issue arises when the order that was initially set for the array changes unexpectedly due to JavaScript manipulation. Originally, the array is ordered as expected when ...

What is the method of duplicating an array using the array.push() function while ensuring no duplicate key values are

In the process of developing a food cart feature, I encountered an issue with my Array type cart and object products. Whenever I add a new product with a different value for a similar key, it ends up overwriting the existing values for all products in the ...

Creating a mapping in Node.js to write to a serial port and then retrieve the

Currently, I am utilizing the node-serialport module for serial port communication. My goal is to send the command ATEC and receive a response of ECHO. However, the process of sending and receiving data is asynchronous (after sending the data, the timing ...

Software designed for the web that utilizes both frontend and backend technologies, including JavaScript

Currently, I am collaborating on a project for a company that created software using Delphi. The software primarily featured a minimalist browser as its central component. This browser was used to analyze webpages, recognize patterns, save data, and more. ...

Emphasizing the chosen element in a list using angular

After retrieving an array of items from the database, my list is constantly changing, causing the HTML display to update dynamically. However, I am struggling with highlighting only the selected item in the list, as the entire list gets highlighted upon se ...

Encountering a Typescript error while attempting to remove an event that has a FormEvent type

Struggling to remove an event listener in Typescript due to a mismatch between the expected type EventListenerOrEventListenerObject and the actual type of FormEvent: private saveHighScore (event: React.FormEvent<HTMLInputElement>) { This is how I t ...

Setting up a .NetCore3.1 API on LinuxCentos with Nginx

Currently, I am facing an issue while attempting to deploy a .NET Core 3.1 API + Angular application on Linux Centos. The application runs fine on the server; however, the browser fails to load it properly. Surprisingly, when I publish the same project for ...

Using Angular and RxJS5 to refresh data from both HTTP requests and sockets

Here's a specific scenario I need to address: Retrieve route parameters Utilize route parameters to make an HTTP service call Upon receiving a response from the HTTP service, use the same route parameters to invoke a socket service Whenever the sock ...

Troubleshooting the malfunctioning save() method in Angular's hero tutorial

Currently working through the Angular Hero Tutorial version 7.3.4 while integrating Angular with a Django backend. Struggling to update a hero's name: Within the hero-detail.component.ts, there is a save() method designed to update the hero object us ...

Utilize the expert capabilities within #dateHeaderTemplate in the Angular component schedule by Syncfusion

I am trying to access the template #dateHeaderTemplate in order to retrieve the ID of the professional who is scheduled to attend the appointment. This information is needed to display the start and end times of the day in the header. By visiting this lin ...

Guide to implement editable columns in Angular 4 with a click functionality

I have a table displaying records using ngFor, and I am looking to enable editing of a column upon clicking it. <tr *ngFor="let cd of descriptionCodes; let i = index"> <td><input type="checkbox"></td> <td> {{cd.code}} ...

Is it feasible to transmit telemetry through a Web API when utilizing ApplicationInsights-JS from a client with no internet connectivity?

My Angular application is running on clients without internet access. As a result, no telemetry is being sent to Azure. :( I am wondering if there is a way to configure ApplicationInsights-JS to call my .Net Core WebApi, which can then forward the inform ...

Commitments when using a function as an argument

While I have a good understanding of how promises function, I often struggle when it comes to passing a function as a parameter: var promise = new Promise(function(resolve, reject) { // Perform asynchronous task ec2.describeInstances(function(err, ...

Displaying errors to the user using Angular's HttpClient in an Ionic application

I am currently working on a small project and struggling to grasp certain TypeScript concepts. Specifically, I am trying to pass data from a form to an object and then send it via an HTTP service to an endpoint. The response is displayed in the console, in ...

The pagination in React using React Query will only trigger a re-render when the window is in

Currently, I am utilizing React-Query with React and have encountered an issue with pagination. The component only renders when the window gains focus. This behavior is demonstrated in the video link below, https://i.sstatic.net/hIkFp.gif The video showc ...

Error encountered while attempting to generate migration in TypeORM entity

In my project, I have a simple entity named Picture.ts which contains the following: const { Entity, PrimaryGeneratedColumn, Column } = require("typeorm"); @Entity() export class Picture { @PrimaryGeneratedColumn() ...

Having trouble authenticating with Google using Angular, Express, and Passport due to a 'No 'Access-Control-Allow-Origin' error?

Scenario In my development project, I'm constructing a stateless application utilizing Angular, Express, and PassportJS for user authentication via Google accounts. The aim is to implement JWT tokens to maintain the application's statelessness. ...

A guide to navigating a JSON array

Utilizing node js, I have extracted the following array by parsing through multiple json files to find a specific value. My json files consist of a collection of IDs with their respective status: isAvailable or undefined. https://i.sstatic.net/AlpVk.png ...

Steps for determining if a string is compatible with a user-defined type in Typescript

Just getting started with Typescript and currently working on a sudoku game. Here are the types and interface I have set up: export type GridCellValue = 1|2|3|4|5|6|7|8|9; export interface GridCell { readonly: boolean, value: GridCellValue|null, } ex ...