使用与bcryptasynchronous的Sequelize

这可能是基于意见的。 但我想得到一些build议。

所以,我想要做的事情可以用这个线程中提到的方式来完成。 但是这个线程为我想要使用asynchronous做了一个好点。

这是我到目前为止,它的工作原理。

User.create({email: req.body.email, password: req.body.password}).catch(function(err){ console.log(err); }); User.beforeCreate(function(user) { const password = user.password; user.password = ''; bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) { if(err) console.error(err); bcrypt.hash(user.password, salt, null, function(err, hash) { if(err) console.error(err); user.password = hash; user.save(); }); }); }); 

由于我使用bcryptasynchronous,我将不得不坚持encryption的密码在另一个查询。 我的直觉告诉我可能有一个更好的方式使用bcryptasynchronous与sequ​​elize。

我的问题是,首选/更好的方法是什么? 或者我应该只是同步使用bcrypt?

asynchronous是一种方式去整理你的代码,并在钩子中使用callback

 function cryptPassword(password, callback) { bcrypt.genSalt(10, function(err, salt) { // Encrypt password using bycrpt module if (err) return callback(err); bcrypt.hash(password, salt, function(err, hash) { return callback(err, hash); }); }); } User.beforeCreate(function(model, options, cb) { debug('Info: ' + 'Storing the password'); cryptPassword(user.password, function(err, hash) { if (err) return cb(err); debug('Info: ' + 'getting ' + hash); user.password = hash; return cb(null, options); }); });