gpt4 book ai didi

javascript - 以异步方式发送网格邮件

转载 作者:行者123 更新时间:2023-12-05 03:00:00 25 4
gpt4 key购买 nike

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);

最佳答案

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

关于javascript - 以异步方式发送网格邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57369068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com