1
我有一個用戶模型是這樣的:節點JS:青鳥Promisify在貓鼬中間件
var Promise = require("bluebird")
var mongoose = require("mongoose");
var mongooseAlias = require('mongoose-aliasfield');
var bcrypt = Promise.promisifyAll(require('bcrypt-nodejs'));
var Schema = mongoose.Schema;
var userSchema = new Schema({
u: { type: String, required: true, trim: true, index: { unique: true }, 'alias': 'userId' },
fb: { type: String, required: true, 'alias': 'fbAccessToken' },
ap: { type: String, required: true, 'alias': 'apiAccessToken' },
f: { type: String, required: true, 'alias': 'firstName' },
l: { type: String, required: true, 'alias': 'lastName' },
e: { type: String, required: true, 'alias': 'email' }
});
// Execute before each user.save() call
userSchema.pre('save', function(callback) {
var user = this;
// return if token hasn't changed
if (!user.isModified('fb') && !user.isModified('ap'))
return callback();
// token changed so we need to hash it
bcrypt.genSalt(5, function(err, salt) {
if (err) return callback(err);
bcrypt.hash(user.fb, salt, null, function(err, hash) {
if (err) return callback(err);
user.fb = hash;
bcrypt.genSalt(5, function(err, salt) {
if (err) return callback(err);
bcrypt.hash(user.ap, salt, null, function(err, hash) {
if (err) return callback(err);
user.ap = hash;
callback();
});
});
});
});
});
userSchema.plugin(mongooseAlias);
module.exports = mongoose.model('User', userSchema);
我努力學習藍鳥的時刻,所以我清理了bcrypt這樣的代碼:
userSchema.pre('save', function(callback) {
var user = this;
// return if token hasn't changed
if (!user.isModified('fb') && !user.isModified('ap'))
return callback();
var p1 = bcrypt.genSaltAsync(5).then(function (salt) {
return bcrypt.hash(user.fb, salt, null);
}).then(function (hash) {
user.fb = hash;
});
var p2 = bcrypt.genSaltAsync(5).then(function (salt) {
return bcrypt.hash(user.ap, salt, null);
}).then(function (hash) {
user.ap = hash;
});
Promise.all(p1, p2).then(function() {
callback();
}).catch(function (err) {
callback(err);
});
});
我可以「進一步promisify」嗎?或者說,我在這裏錯過了什麼可以讓它更優雅的東西?我需要以某種方式promisify userSchema.pre電話嗎?
乾杯