Home > Net >  Is a promise resolved when I add .catch to it?
Is a promise resolved when I add .catch to it?

Time:12-28

I am new to typescript / javascript, so I don't know much about promises. Here is my use-case: I am creating three different promises inside my cloud-function and then returning it with Promise.all([promise1, promise2, promise3]). Each of these promises are created inside a function with "return Promise...".

My question is, when I add ".catch" inside these functions, will Promise.all still work?. Does it make any difference returning someServiceThatCreatesPromise() with and 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}`
   }
}

// Difference with and without `.catch`?
function createFirstPromise() {
   return someServiceThatCreatesPromise().catch((err) => { // LOGGING });
}

// Difference with and without `.catch`?
function createSecondPromise() {
   return someServiceThatCreatesPromise().catch((err) => { // LOGGING });
}

// Difference with and without `.catch`?
function createThirdPromise() {
   return someServiceThatCreatesPromise().catch((err) => { // LOGGING });
}

CodePudding user response:

Adding .catch inside createNPromise won't affect anything assuming all your Promises resolve and do not reject.

However, if one of the Promises rejects and you catch it within the .catch method, then it won't work as you're expecting unless you re-throw that error and catch it again inside the try/catch in your myCloudFirestoreFunction function.

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 work, e.g. log, then
    // pass the error forward so that it can be caught
    // inside the caller
    throw e;
  });
}

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

myCloudFirestoreFunction();

Alternatively, you just catch errors inside the caller (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();

CodePudding user response:

when I add ".catch" inside these functions, will Promise.all still work?

Calling catch() on a promise does not in any way change the way the original promise works. It is just attaching a callback that gets invoked when the first promise becomes rejected, and also returning another promise that resolves after the original promise is fulfilled or rejected.

Does it make any difference returning someServiceThatCreatesPromise() with and without .catch()?

It would not make any difference to the code that depends on the returned promise. Both the original promise and the one returned by catch() will tell downstream code when the original work is done by becoming fulfilled.

I suggest reading comprehensive documentation on promises, for example:

There is a diagram in there that you can follow to understand what happens at each turn. Also in that document, you will read:

Processing continues to the next link of the chain even when a .then() lacks a callback function that returns a Promise object. Therefore, a chain can safely omit every rejection callback function until the final .catch().

  • Related