If the promise does not come to fruition, handle the setback and move on to

Presently, my code looks like this:

const promise1 = aPromiseCall().then(r => logger(r)).catch(e => logger(e));

const promise2 = anotherPromiseCall().then(r => logger(r)).catch(e => logger(e));

Within an async function, I execute the following:

const results = Promise.all([promise1, promise2]);

I have structured it in this manner to ensure that if promise1 fails, promise2 can still be executed. However, I am uncertain whether this is the most optimal approach. Should I include those then, catch statements in each individual promise, or is there a more conventional way to achieve the same result?

Additionally, I want to guarantee that ALL promises are either resolved or rejected before proceeding with the execution of my code, which is why I grouped them within a Promise.all block.

Answer №1

For information on how to handle errors in Promise.all, please visit this link

Promise.all operates on an all-or-nothing basis. It will only resolve once all promises in the array have resolved, or it will reject as soon as one of them rejects. In simpler terms, it either resolves with an array of all resolved values, or rejects with a single error.

You can implement code similar to this example-

Promise.all([promise1, promise2]).then(r => console.log(r)).catch(e => console.log(e));

If you are looking for a solution to a specific issue, you can check out this resource.

let a = new Promise((res, rej) => res('Resolved!')),
    b = new Promise((res, rej) => rej('Rejected!')),
    c = a.catch(e => { console.log('"a" failed.'); return e; }),
    d = b.catch(e => { console.log('"b" failed.'); return e; });

Promise.all([c, d])
  .then(result => console.log('Then', result)) // Then ["Resolved!", "Rejected!"]
  .catch(err => console.log('Catch', err));

Promise.all([a.catch(e => e), b.catch(e => e)])
  .then(result => console.log('Then', result)) // Then ["Resolved!", "Rejected!"]
  .catch(err => console.log('Catch', err));

Answer №2

Quoting from the MDN:

If any of the elements in Promise.all are rejected, the entire promise is rejected. For instance, if you provide four promises that resolve after a timeout and one promise that rejects instantly, then the overall Promise.all will be immediately rejected.

To handle potential rejections effectively:

const promise1 = makeAPromiseCall();        
const promise2 = makeAnotherPromiseCall();


// Within your async function:

const results = await Promise.all([
  promise1.catch(error => error),
  promise2.catch(error => error),
]);

console.log(results[0])
console.log(results[1])

var promise1 = new Promise((resolve, reject) => { 
  setTimeout(() => resolve('resolved'), 2000); 
}); 

var promise2 = new Promise((resolve, reject) => {
  setTimeout(() => reject('rejected'), 1000); 
});

(async function() {
  const results = await Promise.all([
    promise1.catch(error => error),
    promise2.catch(error => error),
  ]);

  console.log(results[0]);
  console.log(results[1]);
})();

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 retrieve an object from a separate function in JavaScript

I am struggling to fetch data from an array and store it in an object. However, every time I try, I end up with either an empty object or a Promise { <pending> } shown in the logs. I have attempted to use a global variable to store the data and acc ...

JavaScript load event causing a race condition

Here is the code snippet I've put together. Please excuse any syntax errors, as I typed this out on my phone. export default class Main extends React.Component { componentDidMount() { axios.get('/user?ID=12345') .then(function (re ...

Assign a value using the select component from Material UI

I just finished creating a dropdown menu const [selectedValue, setSelectedValue] = useState(''); const handleSelectionChange = (e: any) => { //setSelectedValue(e) console.log('value', selectedValue) } .... <Fo ...

Initiating a node request utilizing the value of the array index as the req parameter

I created a method to insert a series of documents into a mongoose collection, with each entry containing the value corresponding to the next index in a range specified by upper and lower bounds. The current implementation works seamlessly when the lower ...

Material-UI web application experiencing crashes due to worn-out cards, resulting in element type being declared as invalid and raising an error

After reviewing numerous similar SO questions, it appears that the issue always comes down to problems with imports. Typically, these involve mistyped import destinations or missing braces, but I have double-checked and found no such issues in my code. ht ...

What is the best way to conceal an HTML element on a particular page that is already styled as (visibility: visible), but only if its child has a specific class assigned to it?

I have a grid of content and posts displayed on multiple webpages. Users can select specific items from the grid to navigate to more detailed information on another page. Each webpage has its own grid which I want to filter based on a specific class. The ...

I am facing difficulties when trying to map the data using react js/axios

After removing the map function from the code, I encountered an error stating that map is not a function. Can someone please assist me with this issue? Here is the updated code: const [text, setText] = useState([]); const axios = require('axios&ap ...

Need to double-click to open my component

Hey there, I just started learning Angular and I'm using Leaflet for my application. I've been able to create some markers, but now I want to open a different component when I click on one of them. This is the code I'm currently using for ...

Using axios from a different directory on a file system

Creating a new folder named services which will contain all the axios actions for Vue. Here's what I have attempted: My save function save() { const CaseController = require("../services/gantt"); CaseController.create(this.data); }, My service f ...

jQuery mobile page transition issue causing white screen error

Currently, I am in the process of using HTML, CSS, and JS to build my PhoneGap project on Eclipse. I have included jQuery and jQuery Mobile libraries in order to utilize the mobile.changepage function within my JS file. However, I am encountering an issue ...

Leveraging Gatsbyjs to Integrate GraphQL Data with Material UI Library

Just starting out as a Frontend Developer and currently learning Gatsbyjs along with the Material UI library. I'm working on creating a new page using the Material UI Gatsby Starter code available here. However, I've encountered an issue when tr ...

Effectively generating observables that extract a designated element from a collection of observables

Within my application, I am utilizing a RxJS subject to broadcast changes within a collection. Each time the collection is updated, the subject emits the new contents as an array format. let collectionSubject = new Rx.BehaviourSubject(); collectionSubjec ...

Utilize AngularJS to inject a value into the jk-rating-stars element

Hello there, I'm wondering how to assign a value to "rating" attribute as "ctrl.rating" using $scope in AngularJS. <jk-rating-stars max-rating="5" rating="ctrl.rating" read-only="ctrl.readOnly" on-rating="ctrl.onRating(rating)"> </jk-rat ...

Visualization of pie charts in Angular2 using Google library

Currently, I am in the process of building a web application using Angular2 that includes a Google pie chart. One of the components of the application is a Directive specifically designed for the pie chart. Below is the code snippet for the Directive: @D ...

CSS fails to render properly on pages containing multiple query strings

An issue was initially reported by a customer using an IE browser (specific version unknown). I was able to reproduce the problem on my Samsung Galaxy 3 mobile's Chrome browser. The CSS is not being applied to the page when accessing this link with tw ...

Autocomplete like Google with arrow key functionality

I have developed a basic search engine that retrieves data from a MySQL database using the PHP "LIKE" function (code provided below). Everything is functioning correctly, but I would like to enhance it so that users can navigate search results with arrow k ...

Having trouble with the toggle button on the Bootstrap 5 navbar?

I am facing an issue with my HTML code where the toggle button does not display properly when I resize the browser screen. Upon clicking on it, the navigation bar items do not show at all. Here is a screenshot of my website <html> <head> ...

Is it possible to utilize AJAX requests in order to create a marker on google maps that updates in real-time?

My goal is to develop an app that generates a real-time updating google map, and I have been advised that AJAX requests can help achieve this. Nevertheless, after studying the documentation, I am uncertain about how to apply this method to solve my issue ...

Executing a script that has been inserted into the page post-loading

I'm facing an issue where the script tag at the bottom of my project is not being executed after adding new pages later on. Main const fetch = (url, call) => { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if ...

What could be causing my resize event to not trigger?

My goal is for the #sequence div to be full height of the browser window when the window size is greater than 920px in height. In such cases, I also want to trigger a plugin. If the window size is lower than 920px, then the height of the #sequence div shou ...