我是初学者,目前正在用 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 文档
Runs an array of functions in series, each passing their results to the next in the array. However, if any of the functions pass an error to the callback, the next function is not executed and the main callback is immediately called with the error.
所以它与 Promise.then 做的工作完全相同,只是链接你的 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
});
你必须在 promises 链的末尾有一个 catch
,并且 then
不应该在另一个 .then
函数中。我可以建议阅读这篇文章 - We have a problem with promises .
关于javascript - 如何在 nodejs 中使用 promise 更改异步回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43581265/