2

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.

Mohammad Yaser Ahmadi
  • 4,664
  • 3
  • 17
  • 39
  • [Never pass an `async function` as the executor to `new Promise`](https://stackoverflow.com/q/43036229/1048572), and avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it) altogether! – Bergi Jan 18 '21 at 14:03

1 Answers1

1

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;
  }
};
Guerric P
  • 30,447
  • 6
  • 48
  • 86
  • I love your way, let's say I want to send mail without waiting –  Jan 18 '21 at 10:42
  • Do you mean send a mail in case of an error? – Guerric P Jan 18 '21 at 10:47
  • No no, I want to send mail, after creating that interview, inside the try block –  Jan 18 '21 at 10:48
  • oh ok then just chain another `Promise` like this: `new InterviewSchedule(...).save().then(sendMail)` assuming `sendMail` is a `function` that returns a `Promise` – Guerric P Jan 18 '21 at 10:50
  • @GuerricP Not `then`. Just put it after the `await` you already have. – Bergi Jan 18 '21 at 14:05
  • @Bergi I guess OP wanted to send a mail after each `InterviewSchedule` instead of waiting for all the `InterviewSchedule` – Guerric P Jan 19 '21 at 14:03