Stop all requests in axios if any of them fail

I've got a series of pending requests lined up

const requests = [];

requests.push(axios.post('/request1', {moo:1});
requests.push(axios.post('/request2', {moo:2});
requests.push(axios.post('/request3', {moo:3});

Promise.all(requests).then((reponse) => {
    debugger;
}).catch((err) => {
    debugger;
});

If any one of them fails, I want to cancel all the requests. But currently, even if one fails, the next request still goes through.

I attempted some cancellation code, but the subsequent request still gets triggered

const requests = [];
const source = axios.CancelToken.source();
const cancelToken = source.token;

requests.push(axios.post('/request1', {moo:1}, {cancelToken} );
requests.push(axios.post('/request2', {moo:2}, {cancelToken} );
requests.push(axios.post('/request3', {moo:3}, {cancelToken} );

Promise.all(requests).then((reponse) => {
    debugger;
}).catch((err) => {
    source.cancel("Request canceled");
    debugger;
});

Answer №1

Despite attempting to cancel the code, subsequent requests are still being triggered.

You're initiating the requests in this section (assuming a closing `)` on each line):

requests.push(axios.post('/request1', {moo:1}, {cancelToken} ));
requests.push(axios.post('/request2', {moo:2}, {cancelToken} ));
requests.push(axios.post('/request3', {moo:3}, {cancelToken} ));

Once those requests are made, `Promise.all` doesn't actually trigger anything; it simply observes processes that are already underway.

Your implementation of cancellation tokens will interrupt the requests when feasible upon the rejection handler executing on the promise of `Promise.all`, but if the requests are initiated concurrently (rather than sequentially), they will all be launched before this occurs.

If you wish to execute the requests one after the other, the simplest method is by using an `async` function:

async function postInSeries(iterable) {
    // Performs requests in sequence
    const results = [];
    for (const request of iterable) {
        results.push(await axios.post(...request));
    }
    return results;
}
// ...
postInSeries([
    ['/request1', {moo:1}],
    ['/request2', {moo:2}],
    ['/request3', {moo:3}],
])
.then(results => {
    // ...utilize the results...
})
.catch(error => {
    // ...manage/report the error...
});

Answer №2

By utilizing a custom library, you have the ability to perform the following actions with ease (Live Demo):

import { CPromise } from "c-promise2";
import CPAxios from "cp-axios";

(async (urls) => {
  try {
    const responses = await CPromise.all(
      function* () {
        for (const url of urls) {
          yield CPAxios(url);
        }
      },
      { concurrency: 3 } // optionally
    );
    console.log(responses);
  } catch (err) {
    console.warn(`Fail: ${err}`);
  }
})([
  "https://rickandmortyapi.com/api/character/1",
  "https://rickandmortyapi.com/api/character/2",
  "https://rickandmortyapi.com/api/character/3",
  "https://rickandmortyapi.com/api/character/4",
  "https://rickandmortyapi.com/api/character/5",
  "https://rickandmortyapi.com/api/character/BadID",
  "https://rickandmortyapi.com/api/character/7",
  "https://rickandmortyapi.com/api/character/8"
]);

You can also implement a mapper function with the help of this library for more efficiency (Live Demo):

import { CPromise } from "c-promise2";
import CPAxios from "cp-axios";

(async (urls) => {
  try {
    const responses = await CPromise.all(urls, {
      mapper(url) {
        return CPAxios(url);
      },
      concurrency: 3
    });
    console.log(responses);
  } catch (err) {
    console.warn(`Fail: ${err}`);
  }
})([
  "https://rickandmortyapi.com/api/character/1",
  "https://rickandmortyapi.com/api/character/2",
  "https://rickandmortyapi.com/api/character/3",
  "https://rickandmortyapi.com/api/character/4",
  "https://rickandmortyapi.com/api/character/5",
  "https://rickandmortyapi.com/api/character/BadID",
  "https://rickandmortyapi.com/api/character/7",
  "https://rickandmortyapi.com/api/character/8"
]);

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

Unable to utilize the "fs" module within a Three.js application

After utilizing this base code to create an app with Three.js, I attempted to incorporate node's fs module for filesystem interaction. Despite adding const fs = require("fs") in my app.js file, the module could not be located. The error mess ...

Validation of HTML forms through JavaScript

I'm working on form validation and struggling with implementing preg_match check from a variable. Currently, I can validate empty fields successfully, but that's not sufficient. Any suggestions on how to proceed? var pattern = /([a-zA-Z0-9]|[a-z ...

Utilizing useEffect in the header component of ReactJS/Next.js: A Comprehensive Guide

In my next.js/react project, I have a component called header.js that is included on every page. Within this component, I've implemented a typewriter effect with rotation by using the following code snippet inside useEffect: export default function H ...

Passport JS receiving negative request

I'm currently experiencing an issue with the passport req.login function. When a user logs in using their email and password, instead of redirecting to /productos2 as intended, it routes to a bad request page. I am utilizing ejs and mongoose for this ...

Moving data from the bottom of the page to the top

I am facing a situation where I have several foreach loops on a page that calculate the sum of variables. By the end of these loops, a specific variable contains data. However, I now need to display this data at the top of my page before the foreach loop. ...

Tips for wrapping a div around its floated children

I'm currently developing a website for an online shopping cart and working on making the search results responsive. I am aiming to display as many items as possible across the screen (usually 3) when viewed on any device with a resolution lower than t ...

Ways to dynamically toggle visibility and hide elements by clicking outside the specified div

I have a div that, when clicked, displays a contact us form. This form toggles between being visible and hidden. How can I make it hide when clicked on another part of the document? Here is the code: function showContactForm(){ var formWidth = &apos ...

Seeking assistance from experienced individuals! Issue with countdown timer functionality in JavaScript

Hey there! I recently started my journey in learning HTML and wanted to create a timer for my website. Although the timer is displaying, the numbers are not showing up and it's not functioning properly. I would really appreciate some assistance from ...

Encounters an undefined error when attempting to access a non-existent value within a nested object in Vue.js

I am currently facing an issue with accessing a nested object property. Here is the scenario: const data={a:'value1',b:{c:'null'}} When trying to access the 'c' property within object 'b', I am encountering a proble ...

Using for loop in AJAX Done() function

I'm currently working on a for loop that loops through an array consisting of 3 different report numbers. For each value in the array, an AJAX request is sent out. What I want to achieve is having a unique behavior for the .done() function based on th ...

What could be causing the .hover function to malfunction and how can I make it so that the .hover function only applies within the corner radius area?

I am attempting to make circles react to my jquery .hover function. Below is the JavaScript code I am using: jQuery.fn.center = function () { this.css("position","absolute"); this.css("top", Math.max(0, (($(window).height() - this.outerHeight()) / 2) + ...

Troubleshooting the problem with JavaScript's week start date

I am encountering an issue with JavaScript when trying to obtain the first day of the week. It seems to be functioning correctly for most cases, but there is a discrepancy when it comes to the first day of the month. Could there be something that I am ove ...

Changing an array in JavaScript within a function

When working with arrays in JavaScript, how can I mutate the value of an array inside a function? I'm aware that certain array methods can achieve this, but regular assignment doesn't seem to work. var arr = [4]; function changeArray(arr) { ...

Exploring the capabilities of Draft JS when integrating with HTML for input and output

It seems like a common request, but I can't seem to find a solution. I've experimented with different plugins such as draft-js-import-html, but they never fully deliver, especially when dealing with images or embedded videos. Here's an exam ...

The damping effect in three.js OrbitControls only activates when the mouse is pressed, however there is no damping effect once the

I find it difficult to articulate: Currently, I am utilizing OrbitControls in three.js and have activated damping for a smoother rotation with the mouse. It is somewhat effective but not entirely seamless. When I click and drag, the damping feature works ...

Exploring the Process of Obtaining _Value Properties within Vue 3 Ref

Hello, I've been attempting to access the values from the _value property in Vue without success. How can I retrieve these values such as accessKey, align, ariaAtomic, etc.? Specifically, I am interested in getting the value of clientWidth. https://i ...

Transmitting data in JSON format containing an array of elements using the axios.post

Within a .vue file, I have implemented a method that concludes with an AJAX call to a Ruby WebService URL using axios.post: send_firma: function () { var person1 = { "identification": "306 ...

The function firebase__webpack_imported_module_2__.auth.createuserwithemailandpassword does not exist

I'm facing an issue with my Firebase setup in my code. The browser console is showing that auth.createUserWithEmailAndPassword() is not a function. Can someone help me troubleshoot this problem? Here's the relevant code from login.js import React ...

Low frame rate in a straightforward Three.js environment on Safari for MacOS

I have created a demo that runs smoothly on Chrome and Firefox but lags terribly on Safari. Disabling antialiasing slightly improves the FPS, but not significantly. I am wondering if there are ways to optimize my code, perhaps by implementing caching techn ...

Dependency tree resolution failed during VUE installation

After pulling my project from another computer where it worked fine, I encountered an error when trying to npm install on this machine. Can someone please provide some guidance on how to resolve this issue and prevent similar problems in the future? npm ER ...