Node.js从一个控制器方法回调到另一个控制器方法

时间:2017-12-06 11:52:04

标签: node.js api express callback nodemailer

我在项目中创建了emailHelper来发送电子邮件。

我希望在电子邮件发送成功后收到回电

//emailHelper.js

module.exports = {
    sendMail: (options) => {
        var transporter = nodemailer.createTransport({
            service: 'SendGrid',
            auth: {
                user: keys.sendGridUsername,
                pass: keys.sendGridPassword
            }
        });
        const mailOptions = {
            from: options.from,
            to: options.to,
            subject: options.subject,
            html: options.content
        };
        transporter.sendMail(mailOptions, (err, info) => {
            if(err) {
                console.log(err);
                return false;
            }
            else {
                console.log('mail sent');
                return true;
            }
        });
    }
}

我只想在发送电子邮件时将数据保存到数据库

const { sendMail } = require('../helpers/emailHelper');
mail: (req, res, next) => {
    const emailOptions = {
        from: 'from@email.com',
        to: 'to@email.com',
        subject: 'subject',
        content: 'text'
    };
    const mailResetLink = sendMail(emailOptions);
    if(mailResetLink) {
        //success save data
    } else {
        //failure trrow error
    }
}

谢谢

1 个答案:

答案 0 :(得分:1)

将您的sendMail包装在承诺中并将其返回:

return new Promise((resolve, reject) => {
       transporter.sendMail(mailOptions, (err, info) => {
            if(err) {
                console.log(err);
                reject();
            }
            else {
                console.log('mail sent');
                resolve();
            }
        });
});

比你能做到的还要多:

sendMail(emailOptions).then(() => {
 // success save data
}).catch(() => {
 // failure trrow error
});

使用async / await你需要更改promise以在任何情况下返回一些标识符,在这种情况下是boolean,而不是调整mail函数:

return new Promise((resolve) => {
           transporter.sendMail(mailOptions, (err, info) => {
                if(err) {
                    console.log(err);
                    resolve(false);
                }
                else {
                    console.log('mail sent');
                    resolve(true);
                }
            });
    });

mail: async (req, res, next) => {
    const emailOptions = {
        from: 'from@email.com',
        to: 'to@email.com',
        subject: 'subject',
        content: 'text'
    };
    const mailResetLink = await sendMail(emailOptions);
    if(mailResetLink) {
        //success save data
    } else {
        //failure trrow error
    }
}