简体   繁体   中英

Return promise-based callback from sequelize-method?

I have a model that looks like this.

var sequelize = require('../database.js').sequelize,
    Sequelize = require('../database.js').Sequelize,

User = sequelize.define('user', {},{
    classMethods: {
        createRider: function(params) {
            var values = [],
                userAttributes = sequelize.models.userAttributes,
                user = User.build(),
                name = userAttributes.build({name: 'name', value: params.name}),
                fbprofile = userAttributes.build({name: 'fbprofile', value: params.fbprofile}),
                phone = userAttributes.build({name: 'phone', value: params.phone});

            user = user.save().then((user) => {
                sequelize.Promise.all([
                    fbprofile.save(),
                    name.save(),
                    phone.save()
                ])
                .then((attributes) => {
                    user.addUserAttributes(attributes);
                });
            });
            return user;
        }
    }
});



module.exports = User;

I call it like this, and wish to ouput some of the userdata:

app.get('/rider/create',
    (req, res) => {
        var User = sequelize.models.user,
        user = User.createRider(req.query);
        res.json(user);
    }
);

as user is defined in a callback promise, .then , it won't contain the userdata when I ouput it. How can I wait to return the data first when the callback is done?

Your createRider method returns a promise, not a value, so you can't assign it like user = User.createRider(req.query); , but you have to wait for the promise to complete.

User.createRider(req.query).then(user => {
  res.json(user);
}

The user object needs to be returned at the end of the promise chain that createRider returns. Since the last expression you return is user.addUserAttributes(attributes) , i assume that user.addUserAttributes(attributes) is also a promise chain that returns the user at the end.

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