简体   繁体   中英

Using Promises in Sequelize Hooks

in the Sequelize documentation I've read that you can use callbacks or return promises inside your hooks . However, the following code fails to work for me – for both the latest 1.x and 2.x versions of 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:

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.

Thank you very much for your help! :)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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