Guarantee: exclude all successful and unsuccessful responses and only carry out the .finally method

I have a function named request:

function request (endpoint) {
  return axios.request(endpoint).then(api.onSuccess).catch(api.onError)
}

api.onSuccess:

  onSuccess (response) {
    let breakChain = false
    ... adding some logic here ...
    return breakChain ? (new Promise(() => {})) : response
  }

api.onError:

  onError (error) {
    let breakChain = false
    ... implementing certain logic here ...
    if (breakChain) {
      return new Promise(() => {})
    } else {
      throw error
    }
  }

api includes various functions representing different API calls depending on endpoint data, and returns request(endpoint).

Currently, I have the code snippet above that returns a Promise with an empty executor always in a pending state to halt subsequent .then(...) and .catch(...) executions, as these handlers are constantly waiting for that Promise to settle. This is specifically used to handle certain API responses with common error handling needs (such as responses with status codes >= 500). The issue now is that I require a call to .finally() (similar to Vue cookbook - https://v2.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html#Dealing-with-Errors) to reset a component's state whether there was an error or not, but this continuous pending Promise approach is posing an obstacle.

The question at hand: Is it feasible to bypass all subsequent .then(...) and .catch(...) calls within one of these handlers and directly proceed to .finally()?

Update: It should be noted that both api.onSuccess and api.onError serve as fundamental handlers. In other components of the application, additional handlers are appended to the end of the basic chain shown in the request function. The typical chain structure for an API call looks something like this:

return axios.request(endpoint).then(api.onSuccess).catch(api.onError).then((response) => {...}).catch(() => {...}).finally(() => {...})

(sometimes missing either .finally() or .catch(...) block)

Answer №1

Is it possible to bypass all subsequent .then(...) and .catch(...) calls within one of those handlers and go straight to .finally()?

No, it's not.

Currently, my solution involves waiting indefinitely - a method using a pending Promise, but this is not ideal.

A better approach would be to skip then handlers by utilizing rejections (exceptions) for flow control, or nesting the section of the chain that needs to be skipped within an if statement.

This is necessary for handling specific API responses that have common response handling requirements, such as responses with codes >= 500.

For this purpose, you can implement something along the lines of:

return axios.request(endpoint).then(response => {
    …
}).catch(error => {
    if (api.handleCommonError(error)) return; // returns false if unable to handle the error
    …
}).finally(() => {
    …
});

It's important to note that hiding this type of error handling inside an api.request function is not recommended.

Answer №2

If you want to make your code asynchronous, you can utilize the async and await features. These are supported by all modern browsers, and your bundler can help ensure compatibility with older browsers.

Here's an example:

async function request (endpoint) {
  try {
    const response = await axios.request(endpoint);
    return api.onSuccess(response);
  } catch (err) {
    api.onError(err);
  } finally {
    // This block always executes, regardless of errors
  }
}

You can also achieve similar functionality using traditional methods:

function request (endpoint) {
  return axios.request(endpoint).then(api.onSuccess, api.onError).then(() => {
    // This code is executed after handling success or error
  }
}

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

Ways to eliminate all attributes and their corresponding values within HTML tags

Hey there, I'm trying to strip away all the attribute values and styles from a tag in html Here's my Input: <div id="content"> <span id="span" data-span="a" aria-describedby="span">span</span> <p class="a b c" style=" ...

Sending data from a Node.js backend to a React.js frontend using res.send

How can I pass a string from my nodejs backend using res.send? app.post("/user", (req,res) => { console.log(req.body.email); res.send('haha'); }); I need to perform certain operations on the front end based on the value of the string retriev ...

Tips for verifying that one of the two input fields is filled in Bootstrap 5 validation

I have implemented Bootstrap validation for the other input fields in this form by using the 'required' attribute. However, for these two specific fields, if at least one is not empty, then the form should be submitted. <form class="needs ...

The feature in DataTables that allows users to choose how many items to display per page is not functioning correctly

My DataTable is experiencing issues with the box that allows you to select how many items per page you want to show. Instead of displaying just the numbers, it shows: [[5,10],[5,10]]. I have tried to troubleshoot this problem without any success. Addition ...

Utilize JSON data loading instead of directly embedding it onto the page for improved website

I've integrated Mention.js into my website, allowing a dropdown list of usernames to appear when "@" is typed in a designated textarea. <textarea id="full"></textarea> While it's functioning well, the examples provided only show how ...

Problem with transitioning to a different page on Next.js

I am having trouble navigating to a different page in Next.js using the router.push function. The goal is to route to "example.js" by utilizing a variable called ChangePage, which leads to a single div element on that page. However, despite following the ...

Adjust the text area to automatically expand or shrink based on the text it contains

Is there a way to automatically adjust the size of a textarea based on its content? Here is the code I am currently using for this purpose: var element = document.getElementById(event.target.id); var content = $(this).val().trim(); if (content == "") { ...

Load an XML file from the local server asynchronously on the Chrome web browser

Attempting to load a local XML/XSL file into a variable for editing seems to be causing an issue. The code provided functions properly in IE and Chrome, however, Chrome displays a warning due to the synchronous nature of the call. function loadXMLDoc(fileN ...

Unable to find 'three' within the three-gltf-loader

I'm facing a new challenge and seeking help here as I couldn't find a solution on my own. I am currently working on a project that combines three.js with Vue.js. The specific error message I received is: Failed to compile. ./node_modules/three- ...

Utilizing Angular 6 and JavaScript to invoke two functions within an (ngClick) event in both the Component and JavaScript

I have a requirement to execute two functions in my click event, one for my component and the other for a custom JavaScript function. Here is the code snippet: Angular click event: <button type="button" class="btn btn-primary" (click)="Plans(); " [att ...

Tips for determining if an item in one array is present in a different array

Looking for a way to disable a button using React code? Take a look at the snippet below: todos.filter(todo => todo.completed === true) .map(todo => todo.id) .includes(this.state.checkedIds) But there's a catch - it always seems to return ...

Retrieve information filtered based on the query parameter

Utilizing react hooks for dynamic data rendering, I am focusing on two main tasks: a. Extracting URL parameters from the component's history props. b. Retrieving state data from the component's history props, which provides an array of objects ...

Is it possible to utilize JavaScript for transmitting and storing data on a server?

Consider this scenario: When you submit a query on stackoverflow, the data you provide is entered into a text field. This information is then transmitted to the server for storage and eventual display to the user. Is it possible to code the functionality ...

Ways to stop React from refreshing the page upon clicking the submit button

Is it possible to prevent a React component from reloading the page when a submit button is pressed? Here is an example of component code: class MyComponent extends React.Component<IEditCampaignStateProps & IEditCampaignDispatchProps, EditCampaignStat ...

Ways to update the DOM following modifications to a data attribute

I'm currently working on a small CMS system that handles translations for static pages in multiple languages. The system refreshes and loads translations dynamically, but I've encountered some bugs that are proving difficult to resolve. One issue ...

Is there a way for me to access the information within these curly brackets [[]}?

I'm facing a challenge where I need to extract the ID from an API response that is formatted in a way unfamiliar to me. As a result, I'm unsure of how to retrieve the ID data from this response. (This is my initial query, so if it's unclear ...

Unlocking Worldwide Availability for Identifying URL Parameters

Is there a way to obtain global access to the current URL ID params? I am facing difficulty accessing the current URL ID in a child component within React. The ID is essential for querying a MongoDB database in my ChecklistTool component. Typically, I wou ...

The interface 'IProduct' does not include several properties found in type 'IProduct[]', such as length, pop, push, concat, and many more

My goal is to transfer data between parent and child components using React and TypeScript. I have defined the following interfaces: export interface IProduct { id: string; name: string; price: string; image: string; ...

The art of concealing and compressing JavaScript code

Can modern JavaScript obfuscation and minification tools effectively protect my code from reverse engineering? Which obfuscation platforms are the most reliable in thwarting these attempts? Is it possible that a program could easily deobfuscate the code, ...

Vertical scrollbar in iframe unexpectedly appears immediately after the submit button is pressed

I have designed a contact form that is displayed in an iframe within an overlay div. I have carefully adjusted the dimensions of this div to ensure that there are no scrollbars visible when the form initially appears. However, after filling out the form an ...