Sunday, 23 April 2017

how to change async callback using promise in nodejs?

I am a beginner and am currently making a User Management system in NodeJS, I had previously done it with MongoDB, Express. Right now im making it all again with Express, Sequelize and Postgresql to better understand some concepts.

What im stuck at is the reset page where I previously used Async.waterfall to get the email id and send email using SendGrid, but now I want to know how can I convert it using Promises..? It is a bit confusing to understand how to use them with concurrent callbacks.

Here is the previous code using the async.waterfall :

app.post('/forgotpassword',function (req, res) {
        async.waterfall([
            function (done) {
                crypto.randomBytes(20).then( function (err, buf) {
                    var token = buf.toString('hex');
                    done(err, token);
                });
            },
            //2nd function
            function (token) {
                Model.User.findOne({where: {'email' : req.body.email}})
                    .then(function (user) {
                        if(!user){
                            req.flash('forgotMsg', 'No account with that email id exists.');
                            return res.redirect('/forgotpassword');
                        }

                        User.resetPasswordToken = token;
                        User.resetPasswordExpires = Date.now() + 3600000;

                        Model.User.create().catch(function (err) {
                            console.log(err);
                        });
                })
            },
            //3rd function
            function (token, user) {
                var nodemailer = require('nodemailer');
                var sgTransport = require('nodemailer-sendgrid-transport');
                var options = { auth: { api_key: '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' } };
                var mailer = nodemailer.createTransport(sgTransport(options));

                var mailOptions = {
                    to : email,
                    from : 'passwordreset@demo.com',
                    subject : 'Node.js Password Reset',
                    text: 'You are receiving this because you (or someone else) have requested the reset of the password for your account.\n\n' +
                    'Please click on the following link, or paste this into your browser to complete the process:\n\n' +
                    'http://' + req.headers.host + '/reset/' + token + '\n\n' +
                    'If you did not request this, please ignore this email and your password will remain unchanged.\n'
                };
                mailer.sendMail(mailOptions)
                    .then(function (user) {
                        req.flash('forgotMsg', 'An E-mail has been sent to ' + user.email + ' with further instructions.');
                    }).catch(function (err) {
                        console.log(err);
                });
            }
        ], function (err) {
            if(err)
                return next(err);
                res.redirect('/forgotpassword');
        })
    });



via Uday Saini

No comments:

Post a Comment