0

I have a function in which I'm sending an email in express using express-mailer:

exports.sendEmail = function (req, res) {
    // various mail server settings here //

    var output = false;

    app.mailer.send(
        'email',
        { to: req.body.to,
          subject: req.body.subject,
          otherProperty: 'Other Property'
        },
        function (err) {
            if (err) {
                // handle error
                console.log(err);
                res.send('There was an error sending the email');
                return;
            }
            output = true;
            console.log('email send');
        }
    );
    return output;
}

Now this code all works and it sends the email like it should. But the return value is false, even though the "email send" string is being displayed in console, so the "output = true" must be executed. From what I've read it should be possible to override a variable inside an inner function as long as you dont redeclare it with "var", so I dont understand why it is not returning true.

Jordan Running
  • 102,619
  • 17
  • 182
  • 182

1 Answers1

0

I'm guessing (can't tell without knowing the implementation details of app.mailer.send) that the send function is asynchronous. So while it does send the mail, the sendEmail function is returning, so you have a race condition.

A typical solution is to execute the callback on success instead of returning a success variable and then doing something with it. Or you could use deferred calls/promises http://www.htmlgoodies.com/beyond/javascript/making-promises-with-jquery-deferred.html

Jeff Storey
  • 56,312
  • 72
  • 233
  • 406