简体   繁体   English

在Sequelize挂钩中使用Promise

[英]Using Promises in Sequelize Hooks

in the Sequelize documentation I've read that you can use callbacks or return promises inside your hooks . Sequelize文档中,我读到可以在钩子中使用回调或返回Promise However, the following code fails to work for me – for both the latest 1.x and 2.x versions of Sequelize. 但是,以下代码对我不起作用–对于最新的1.x和2.x版本的Sequelize。

I setup the user model: 我设置了用户模型:

var User = function(sequelize, DataTypes) {
    var User = sequelize.define('User', {
        firstName: DataTypes.STRING,
        lastName: DataTypes.STRING,
        email: DataTypes.STRING,
        password: DataTypes.STRING
    }, {
        hooks: {
            beforeUpdate: _hashPassword,
            beforeCreate: _hashPassword
        }
    });

    return User;
};

This is my function that hashes the user's password, using promises (doesn't work): 这是我的功能,它使用诺言(不起作用)对用户的密码进行哈希处理:

function _hashPassword(user) {
    if (!user.getDataValue('password')) {
        return Promise.reject();
    }

    return bcryptGenSalt(10)
        .then(function(salt) {
            return bcryptHash(user.getDataValue('password'), salt);
        })
        .then(function(hash) {
            user.setDataValue('password', hash);

            return user;
        });
}

I can't create users with the hooks setup like this. 我无法使用类似的钩子设置来创建用户。 I don't get an error, but nothing happens – no users are created / saved to the database. 我没有收到错误,但是什么也没发生–没有用户创建/保存到数据库。 If I change my _hashPassword(user) method to call a callback function on success instead of returning the promise, the user is created and the password is successfully hashed: 如果我更改_hashPassword(user)方法以在成功时调用回调函数而不是返回诺言,则将创建用户并成功对密码进行哈希处理:

This is my hash function that uses the callback (works): 这是我使用回调的哈希函数(有效):

function _hashPassword(user, cb) {
    if (!user.getDataValue('password')) {
        return Promise.reject();
    }

    bcryptGenSalt(10)
        .then(function(salt) {
            return bcryptHash(user.getDataValue('password'), salt);
        })
        .then(function(hash) {
            user.setDataValue('password', hash);

            cb(null, user);
        });
}

I would really like to use promises for this to keep things consistent. 我真的很想使用诺言来保持事情的一致性。 Am I missing something? 我想念什么吗? Is this a bug or is there an error in the documentation? 这是错误还是文档中有错误? This behaviour is the same in the latest 1.x and 2.x versions of Sequelize for me. 对于我来说,最新的1.x和2.x版本的Sequelize中的这种行为是相同的。

Thank you very much for your help! 非常感谢您的帮助! :) :)

您可以在此处使用续集承诺

return sequelize.Promise.reject('Some Error');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM