sendgrid-nodejs icon indicating copy to clipboard operation
sendgrid-nodejs copied to clipboard

Update quickstart example to include promises (for use in Vercel)

Open j2is opened this issue 4 years ago • 1 comments

Issue Summary

Within a serverless function such as Vercel it's nice to encapsulate the sending function within a promise to ensure that it completes before the job is terminated. Also checking for an API key in case it's not added by mistake

Code Snippet

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

if (!process.env.SENDGRID_API_KEY) {
  throw new Error("Missing API key");
}

const msg = {
  to: '[email protected]',
  from: '[email protected]', // Use the email address or domain you verified above
  subject: 'Sending with Twilio SendGrid is Fun',
  text: 'and easy to do anywhere, even with Node.js',
  html: '<strong>and easy to do anywhere, even with Node.js</strong>',
};

const sendMail = (msg) => {
  return new Promise((resolve, reject) => {
    sgMail
      .send(msg)
      .then(response => {
        resolve(response);
      }, error => {
        reject(error);
      });
    });
};

//ES6
sendMail(msg).then(() => {}, error => {
  console.error(error);

  if (error.response) {
    console.error(error.response.body)
  }
});

//ES8
(async () => {
  try {
    await sendMail(msg);
  } catch (error) {
    console.error(error);
    if (error.response) {
      console.error(error.response.body)
    }
  }
})();

Technical details:

  • sendgrid mail: ^7.4.6
  • node version: 14.x

j2is avatar Aug 31 '21 13:08 j2is

This issue has been added to our internal backlog to be prioritized. Pull requests and +1s on the issue summary will help it move up the backlog.

eshanholtz avatar Sep 07 '21 19:09 eshanholtz