Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node js - how do I return a value from a function when it depends on asynchronous function inside

I've written a node js module that sends emails. The module is a wrapper for the nodemailer module. When the callback of transporter.sendMail is executed, I want my wrapper function to return true if the email was sent, or false otherwise. How can I do this? Here's the code:

var nodemailer = require('nodemailer');

module.exports.sendEmail = function (mailerAddress, mailerPassword, to, subject, html) {
var transporter, mailOptions;

transporter = nodemailer.createTransport({
    service: 'Gmail',
    auth: {
        user: mailerAddress,
        pass: mailerPassword
    }
}); 

mailOptions = {
    from: mailerAddress, 
    to: to,
    subject: subject,
    html: html
};

transporter.sendMail(mailOptions, function(error, info) {
    if (error) {
        return false;
    }
    else {
        return true;
    }
});         
};
like image 429
Mister_L Avatar asked Feb 09 '23 14:02

Mister_L


1 Answers

If I understood, the "wrapper function" that you're saying is the callback function, so if I I'm correct, try to do something like this:

var EmailUtil = {
    sendEmail : function sendEmail(mailerAddress, mailerPassword, to, subject, html, callback) {
        var options = {
            service: 'Gmail',
            auth: {
                user: mailerAddress,
                pass: mailerPassword
            }
        };
        var transport = nodemailer.createTransport(options);

        transport.sendMail({
            from: mailerAddress, 
            to: to,
            subject: subject,
            html: html
        }, function(err, responseStatus) {
            var val;
            if (error) {
                val = false;
            } else {
                val = true;
            }
            callback(error, val);
        });
    }
};

module.exports = EmailUtil;

This is a real example that I use in production.

like image 57
danilodeveloper Avatar answered Feb 12 '23 09:02

danilodeveloper