0

I have an Array of promises that are processing a mail queue. I am using Promise.all() to handle this array of promises.

let mails = data.result;
    let promises = [];
    mails.forEach(mail => {
        let mailOptions = {
            from: mail.mail_from,
            to: mail.mail_to,
            subject: mail.subject,
            [mail.mail_type]: mail.body
        };
        promises.push(helper.sendMail(mailOptions));
    });
    Promise.all(promises)
    .then(data => {
        // update mail queue status in the database.
    }).catch(err => console.log(err));

Now If there occurs an error while sending any of the emails then the code that updates the mail status in the database does not execute.

Is there a way to let the execution of code occur even if there is an error.

In other words, I want then to be executed everytime a mail is sent successfully otherwise catch should be called but the rest of the mail queue should also be processed.

Amarjit Singh
  • 2,068
  • 19
  • 52

1 Answers1

1

For what I understand you want to execute then or catch for each promise, right?

const mails = data.result;
mails.forEach(mail => 
  helper
    .sendMail({
      from: mail.mail_from,
      to: mail.mail_to,
      subject: mail.subject,
      [mail.mail_type]: mail.body,
    })
    .then(data => {
      // update mail queue status in the database.
    })
    .catch(err => console.log(err))
)

if that is not what you meant, comment and I'll try to help you out

karran
  • 304
  • 1
  • 6