Reputation: 15006
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?
Upvotes: 0
Views: 1149
Reputation: 1350
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.
Upvotes: 1