簡體   English   中英

如何在nodejs中使用promise更改異步回調?

[英]how to change async callback using promise in nodejs?

我是一個初學者,目前正在使用NodeJS制作用戶管理系統,我以前是使用MongoDB Express來完成的。 現在,我通過Express,Sequelize和Postgresql再次進行了全部處理,以更好地理解一些概念。

我停留在復位頁面上的是我以前使用Async.waterfall來獲取電子郵件ID並使用SendGrid發送電子郵件的重置頁面,但是現在我想知道如何使用Promises ..將其轉換。 了解如何將它們與並發回調一起使用有點令人困惑。

這是先前使用async.waterfall的代碼:

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

                user.local.resetPasswordToken = token;
                user.local.resetPasswordExpires = Date.now() + 3600000; // 1 hour

                user.save(function(err) {
                    done(err, token, user);
                });
            });
        },
        //3
        function(token, user, done) {

            var nodemailer = require('nodemailer');
            var sgTransport = require('nodemailer-sendgrid-transport');

            var options = {
                auth: {
                    api_key: ''
                }
            };

            var mailer= nodemailer.createTransport(sgTransport(options));

            var mailOptions = {
                to: user.local.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, function(err) {
                req.flash('forgotMessage', 'An e-mail has been sent to ' + user.local.email + ' with further instructions.');
                done(err, 'done');
            });
        }
    ],
    //2 out of Async
    function(err) {
        if (err) return next(err);
        res.redirect('/forgotpassword');
    });
});

來自async.waterfall文檔

依次運行一個函數數組,每個函數將其結果傳遞給數組中的下一個函數。 但是,如果有任何函數將錯誤傳遞給回調,則不會執行下一個函數,並且會立即以錯誤調用主回調。

因此,它與Promise完全相同,然后做,只是兌現您的諾言。

    crypto.randomBytes(20)
    .then( function (buf) {
         var token = buf.toString('hex');
         return token;
    })
    .then( function(token) {
       return Model.User.findOne({where: {'email' : req.body.email}});
    })
    .then(function (user) {
         if(!user){
            //    throw no user found error             
         }

         return Model.User.create();

    })
    .catch( function(err) { 
       // error handling
       // catch no user found error and show flash message
    });

您必須在Promise鏈的末尾具有單個catchthen不應位於另一個.then函數內部。 我可以建議閱讀這篇文章- 我們對諾言有疑問

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM