How to use map inside try/catch?

Viewed 362

I have a sample, kindly have a look, if I am doing it the right way,

export const create = async ({ invitationList, testId }) => {
  try {
    const promises = invitationList.map(async invitationTo => {
      return new Promise(async (resolve, reject) => {
        const invitation = await InterviewSchedule({
          invitationTo,
          testId
        }).save();
        resolve(invitation);
      });
    });
    Promise.all(promises).then(value => {
      console.log(value);
    });
  } catch (error) {
    throw error;
  }
};

I am unable to catch the error inside the catch block.

1 Answers

The classic try/catch control flow for errors only works when you await the promises. In your code, you are not awaiting the Promise.all. Try this instead:

export const create = async({
  invitationList,
  testId
}) => {
  try {
    const promises = invitationList.map(invitationTo =>
        new InterviewSchedule({
          invitationTo,
          testId
        }).save());
    const results = await Promise.all(promises);
    console.log(results);
  } catch (error) {
    throw error;
  }
};
Related