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: '[email protected]',
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);
}
}
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: '[email protected]',
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);
}
}
I have this code snippet in my nodejs project. Which is working correctly. But the only problem is this isn't work in async manner. I try to find that in the official docs and I couldn't find that in there. Putting await
in the send
function, is that all I need to do to make this work as an async function.
await sgMail.send(msg);
Share
Improve this question
asked Aug 6, 2019 at 4:43
margherita pizzamargherita pizza
7,22729 gold badges103 silver badges178 bronze badges
3
- Are you concerned about response here ? Do you really need to check response ? if not then let it be fire and forget. – CoronaVirus Commented Aug 6, 2019 at 4:59
-
this isn't work in async manner
what do you mean? Why have you made the functionasync
if you are never usingawait
? – Jaromanda X Commented Aug 6, 2019 at 4:59 -
perhaps if you read some documentation and use the Promises that
.send
returns, you'd get asynchrony :p ... quick fix ...await sgMail.send(msg);
... done – Jaromanda X Commented Aug 6, 2019 at 5:03
1 Answer
Reset to default 6They added example to send async in GitHub
Here is the code:
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_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>',
};
//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)
}
}
})();