【问题标题】:send grid mail in async way以异步方式发送网格邮件
【发布时间】:2019-08-06 04:43:00
【问题描述】:

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 项目中有这段代码 sn-p。哪个工作正常。但唯一的问题是这不能以异步方式工作。我尝试在官方文档中找到它,但在那里找不到。将await 放入send 函数中,我需要做的就是使其作为异步函数工作。

await sgMail.send(msg);

【问题讨论】:

  • 您是否担心这里的反应?你真的需要检查响应吗?如果没有,那就让它着火然后忘记。
  • this isn't work in async manner 什么意思?如果你从不使用await,为什么还要创建函数async
  • 也许如果你 read some documentation 并使用 .send 返回的承诺,你会得到异步:p ...快速修复 ... await sgMail.send(msg); ...完成

标签: javascript sendgrid


【解决方案1】:

他们在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)
    }
  }
})();

【讨论】:

    猜你喜欢
    • 2012-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多