Does adding .catch resolve a promise?

Being new to typescript / javascript, I have limited knowledge about promises. My current scenario involves creating three distinct promises within a cloud-function and subsequently returning them using

Promise.all([promise1, promise2, promise3])
. Each of these promises is generated within a function that includes the statement "return Promise...".

I am curious as to whether adding ".catch" inside these functions will impact the functionality of Promise.all. Does it matter if someServiceThatCreatesPromise() is returned with or without .catch()?

Code

export async function myCloudFirestoreFunction() {
   try  {
        const myFirstPromise = createFirstPromise()
        const mySecondPromise = createSecondPromise()
        const thirdPromise = createThirdPromise()

        return Promise.all([
          myFirstPromise,
          mySecondPromise,
          myThirdPromise
       ]);
   } catch (err) {
       functions.logger.err(`Something bad happened, See: ${(err as Error).message}`
   }
}

// What happens when using `.catch` vs. not using it?
function createFirstPromise() {
   return someServiceThatCreatesPromise().catch((err) => { // LOGGING });
}

// What happens when using `.catch` vs. not using it?
function createSecondPromise() {
   return someServiceThatCreatesPromise().catch((err) => { // LOGGING });
}

// What happens when using `.catch` vs. not using it?
function createThirdPromise() {
   return someServiceThatCreatesPromise().catch((err) => { // LOGGING });
}

Answer №1

When adding .catch inside the createNPromise function, it will not have any impact if all your Promises are resolving without any rejections.

However, in case a Promise gets rejected and you try to catch it using the .catch method, it may not work as expected unless you throw the error again and catch it within a try/catch block in your myCloudFirestoreFunction.

async function myCloudFirestoreFunction() {
  try {
    const result = await Promise.all([
      createFirstPromise(),
      createSecondPromise()
    ]);
  } catch (error) {
    console.log({ error });
  }
}

function createFirstPromise() {
  return Promise.reject("Oof").catch((e) => {
    // do some work, e.g., logging, and then
    // throw the error so it can be caught by the caller
    throw e;
  });
}

function createSecondPromise() {
  return Promise.resolve("value");
}

myCloudFirestoreFunction();

Another approach is to simply handle errors within the caller function (myCloudFirestoreFunction) instead of catching them separately.

async function myCloudFirestoreFunction() {
  const result = await Promise.all([
    createFirstPromise(),
    createSecondPromise()
  ]).catch((err) => console.log({ err }));
}

function createFirstPromise() {
  return Promise.reject("Oof");
}

function createSecondPromise() {
  return Promise.resolve("value");
}

myCloudFirestoreFunction();

Answer №2

Can I still use Promise.all if I add ".catch" inside these functions?

Utilizing catch() within a promise does not interfere with the functionality of the original promise. It simply adds a callback to handle rejection, while also returning another promise that resolves after the initial one completes.

Is there any impact on someServiceThatCreatesPromise() when using it with or without .catch()?

The presence or absence of catch() does not affect how the returned promise is used in code downstream. Both the original promise and the one generated by catch() indicate when the work is complete by being fulfilled.

For a more thorough understanding of promises, consider exploring detailed documentation such as:

This resource includes a helpful diagram to guide you through the process. Additionally, the document explains:

Even if a .then() does not contain a callback function returning a Promise object, processing will proceed to the next link in the chain. As a result, every rejection callback can be omitted until reaching the final .catch().

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

Dynamically load a custom element with a Component

I am attempting to dynamically inject a component into a container. Component: @Component({...}) export class InvestmentProcess{ @ViewChild('container') container; constructor(public dcl: DynamicComponentLoader) {} loadComponent(fo ...

Exploring the method of extracting multiple checkbox values from an HTML form

While I'm aware that jQuery can be used to retrieve checkbox values when there are multiple checkboxes, the solutions available online don't seem to work for me. This is because my checkbox inputs are embedded within an HTML form, and none of the ...

Sticky header in React data grid

Is there a way to implement a sticky header for a data grid in react? I have tried various methods but haven't been able to figure it out. Any suggestions would be appreciated. You can find my code sandbox example here. #react code export const Styl ...

Is there a CSS3 Selector With Similar Functionality to jQuery's .click()?

For a few years now, I have been utilizing a pure CSS navigation system. However, with the recent increase in mobile site projects at my workplace, I am encountering issues with drop-down menus not functioning properly on mobile devices. Despite this chall ...

The Selenium driver's execute_script() function is not functioning as expected

When I attempt to execute a JavaScript using driver.execute_script, nothing happens and the system just moves on to the next line of Python code. Any ideas? I've been web scraping on a webpage, using JavaScript in the Console to extract data. The Jav ...

Iterating through an array of objects and performing reduction based on various key-value pairs

I am faced with a challenge of consolidating a large array of objects into one single array that has a specific structure. Each item, such as a banana, needs to be present in two separate objects for buy orders and sell orders, each with their own distinct ...

Access the value of a variable passed from the view to the controller

Is there a way to retrieve a dynamically generated value from the view to the controller in AngularJS? <ng-option ng-repeat="w in details track by $index"> <div class="program-grid-row table-row" > <div> <a class= ...

Regularly send requests to an Express server using the $.get function

Operating an Express server with a time generator to send generated time data to the client page gtm.hbs. How can I implement regular polling of the server from the client using Ajax? Displayed below is the server-side code located in \routes\ge ...

The alert function in the Ajax web method is malfunctioning

Every time I try to call the Ajax web method, I keep receiving a 'save error' message. However, the data is successfully saved to the database without any issues. I have checked for errors but couldn't find any. How can I display an alert sa ...

Is there a way for me to access the source code of elements within React Native?

Currently, I am working on writing code using React Native and compiling it in Android Studio with an emulator. When I press ctrl+m on the emulator and select "show inspector" to click on elements, I am unable to see which line of code corresponds to the s ...

Sort the array based on the enum name rather than its value

Below is an example of an enumeration: export enum Foo { AA = 0, ZZ = 1, AB = 2, ER = 5 } In my case, I want to sort my Bars based on the name of the enum (AA, AB, ER, ZZ), rather than the numerical value (0, 1, 2, 5) that they represent. ...

Having trouble with ReactJS rendering components?

FriendList.js var React = require('react'); var Friend = require('./friend.js'); var FriendList = React.createClass({ render: function() { return( <div> <h3& ...

Using React.js CSSTransition Component properties with TransitionGroup

Exploring ways to animate a group of divs has led me to discover this example which perfectly fits my needs. However, as I am still new to React, I'm having trouble understanding how the props are passed through the <Fade> component, specificall ...

When using Inertia.js with Typescript, an issue arises where the argument types {} and InertiaFormProps{} are not compatible with the parameter type Partial<VisitOptions> or undefined

I set up a brand new Laravel project and integrated Laravel Breeze along with Typescript support. After creating a form (using useForm()) and utilizing the .post() method with one of the options selected (such as onFinish: () =>), I encountered the fol ...

Is it possible to pass arguments to setTimeout function?

At the current moment, my code looks like this: function showGrowl(lastNumber) { var num = lastNumber; //keep generating a random number untill it is not the same as the lastNumber used while((num = Math.ceil(Math.random() * 3)) == lastNumber); ...

Strange compilation issue "Syntax error: Unable to access 'map' property of null" occurs when map function is not utilized

I recently developed a custom useToggle hook that does not rely on the .map() method: import { useState } from "react"; export const useToggle = ( initialValue: boolean = false ): [boolean, () => void] => { const [value, setValue] = us ...

What are the steps to successfully submit my form once all the validation requirements have been met?

I successfully completed the validation process, but I am encountering an issue when trying to submit the form. An error message pops up indicating that there is an error related to a specific field (e.g., special characters being used). However, even when ...

How can I implement a feature to automatically close a drawer in a React application using the Material UI

Currently, I am utilizing a React material design theme However, I am facing an issue where the drawer navigation button on mobile view does not close automatically upon clicking I need something like (onClick={handleClose}) to resolve this problem Does ...

Enhance the way UV coordinates are generated for rotated triangles/faces within THREE.js

While researching how to map a square texture onto n-sided polyhedrons using a convex hull generator in THREE.js, I found that existing solutions did not fully address my issue. The challenge was to ensure that the texture was not distorted and appeared co ...

Enabling real-time notifications through Express 4 middleware with socket.io integration

I am in the process of developing a real-time notification system utilizing socket.io. Here is the current server-side code I have implemented: bin/www: var app = require('../app'); var server = http.createServer(app); var io = app.io io.attac ...