以异步方式发送网格邮件

时间:2019-08-06 04:43:00

标签: javascript sendgrid

const sgMail = require('@sendgrid/mail');

const {
  keys,
} = require('../../config/config');

async function forgotPassword(req, res) {
  
  try {
    //...
    sgMail.setApiKey(keys.sendGridKey);
    const msg = {
      to: `${req.body.email}`,
      from: 'no-reply@example.com',
      subject: 'Forgot password request',
      text: 'You get this email because of you asked to reset password',
      html: `<strong>${token}</strong>`,
    };
    sgMail.send(msg);
   
    res.sendStatus(200);
  } catch (error) {
   
    res.status(500).json(error.message);
  }
}

我的nodejs项目中有此代码段。哪个工作正常。但是唯一的问题是这不能以异步方式工作。我尝试在官方文档中找到它,但在那里找不到。将await放在send函数中,是我需要做的所有工作才能使其成为异步函数。

await sgMail.send(msg);

1 个答案:

答案 0 :(得分:2)

他们添加了在 GitHub 中发送异步的示例

代码如下:

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
  to: 'test@example.com',
  from: 'test@example.com', // 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>',
};
//ES6 Old way
sgMail
  .send(msg)
  .then(() => {}, error => {
    console.error(error);

    if (error.response) {
      console.error(error.response.body)
    }
  });
//ES8 - Async example
(async () => {
  try {
    await sgMail.send(msg);
  } catch (error) {
    console.error(error);

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