陷入快速回调地狱

时间:2017-09-20 18:20:37

标签: node.js express callback promise nodemailer

成功发送电子邮件后,我无法取消请求。发送电子邮件后如何正确返回?这可能是一个回调地狱,但我无法弄清楚如何解决它。

我试图在不同的部分进行一些回报,但它没有用。

const router        = require('express').Router();
const nodemailer    = require('nodemailer');
const emailExistence= require('email-existence');

module.exports = router;

// Send email when user has forgotten his/her password
router.post('/forgetPass', (req, res, next) => {
    if(!req.body.email){
        next(new Error("Email is required."));
        return;
    }

    emailExistence.check(req.body.email, function(err,res){

        if(err || !res){
            next(new Error("The email does'nt exist."));
            return;
        }else{
            let transporter = nodemailer.createTransport({
                service: 'gmail',
                auth: {
                    user: 'myemail@gmail.com',
                    pass: 'mypassword'
                }
            });

            let mailOptions = {
                from:       'myemail@gmail.com',
                to:          req.body.email,
                subject:    'Link for setting a new password',
                html:       'Set a new password'
                text:       'email text'    
            };


            transporter.sendMail(mailOptions, function(error, info){
                if (error) {
                    next(new Error("Error in sending email."));
                    return;
                }

                res.json(Object.assign(req.base, {
                    message: "The email has been sent successfully.",
                    data: info
                }));
                return;

            });
        }
    });
});

2 个答案:

答案 0 :(得分:2)

成功发送后设置响应字段,最后一步调用next(),以便下一个中间件获取请求并发回响应。所以基本上:

...
res.json(yourResponse);
next();
...

或者,如果这是最后一个中间件,请将响应发送回客户端:

res.send(yourResponse);

答案 1 :(得分:0)

我以这种方式解决了它。 emailExistence不允许我使用promises,因此我使用了email-ckeck而不是它:

const router        = require('express').Router();
const nodemailer    = require('nodemailer');
const emailExistence= require('email-existence');
var emailCheck      = require('email-check');

module.exports = router;

router.post('/forgetPass', (req, res, next) => {
    if(!req.body.email){
        next(new Error("Email is required."));
        return;
    }

    // Check the req.body.email with email pattern regex
    var patt = new RegExp (process.env.EMAIL_PATTERN__REGEX),
        isEmail = patt.test(req.body.email);    

    if(!isEmail){
        next(new Error("The email does'nt seem to be a valid email. If you are sure about your email validity contact the website admin."));
        return;
    } 

    return emailCheck(req.body.email)
        .then(function(result){
            let transporter = nodemailer.createTransport({
                service: 'gmail',
                auth: {
                    user: process.env.EMAIL,
                    pass: process.env.EMAILPASSWORD
                }
            });

            let mailOptions = {
                from:       process.env.EMAIL,
                to:         req.body.email,
                subject:    'Link for setting a new password',
                html:       'Set a new password from <a href="http://www.example.com/newpass">this link</a>.'    
            };

            return transporter.sendMail(mailOptions)
                .then(function (result2) {
                            res.status(200).json(Object.assign(req.base, {
                                message: "The email has been sent successfully.",
                                data: null
                            }));
                            return;
                        },
                        function(error2){
                            next(new Error("Error in sending email."));
                                return;
                        });
        },
        function(error) {
            next(new Error("The email does'nt seem to be a valid email. If you are sure about your email validity contact the website admin."));
            return;
        });
});