我的初始化事件未按预期顺序运行。
我的Bookshelf模型中有以下生命周期事件侦听器:
initialize: function() {
this.on('saving', this.validate);
this.on('creating', this.generateId);
this.on('creating', this.hashPassword);
this.on('creating', this.generateUsername);
}
我在" generateUsername'中返回一个承诺方法。根据日志,这个承诺在“验证”之后完成。方法运行。
我的印象是生命周期事件是Promise-aware,并且会在继续之前等待Promise完成。我做错了什么?
生命周期方法:
generateId: function() {
this.set('id', shortid.generate());
},
hashPassword: function() {
/* eslint-disable no-invalid-this */
return bcrypt.genSaltAsync(12).bind(this)
.then(function(salt) {
return bcrypt.hashAsync(this.get('password'), salt);
})
.then(function(hash) {
this.set('password', hash);
});
},
generateUsername: function(model, attr, options) {
var email = this.get('email');
if (!email) {
this.set('username', shortid.generate());
return;
}
var username = email.substring(0, email.indexOf('@')).replace(/[^a-z0-9_-]/g, '');
if (!username) {
this.set('username', shortid.generate());
return;
}
var self = this;
return User.where('username', '=', username)
.fetch()
.then(function(found) {
if (!found) {
self.set('username', username);
winston.info('setting username to [%s]', username);
} else {
self.set('username', username + shortid.generate());
winston.info('setting username to [%s]', self.get('username'));
}
});
},
validate: function() {
return checkit.run(this.attributes);
}
日志:
info: Validation errors { username: [ 'The username is required' ],
ageGroup: [ 'The ageGroup is required' ],
bodyType: [ 'The bodyType is required' ] }
info: setting username to [nim_sathiVyxIkm--Hx]