Reputation: 1027
I'm having trouble with what I think are Javascript closures? I have an Express + Mongoose web app and am using the Q library for Promises.
I am wondering if it's possible to pass request data to the promise chain so that I can successfully execute the below code.
Currently, I am not able to set review.reviewer
and review.application
. The only solution I can think of currently is to append the request data to the req.body
object so that all of this is handled on Review.create
(see alternative solution code). Still, I am not sure if this is an ideal solution and whether or not it's possible to pass req data into a promise.
create: function(req, res) {
console.log('Creating obj');
Review.create(req.body).then(function(review) {
Q.all([
function() {
review.reviewer = req.user.id;
review.application = req.params.applicationId;
return review.save();
},
User.findByIdAndUpdate(review.reviewer, {$push: {reviews: review._id}}).exec(),
Application.findByIdAndUpdate(review.application, {$push: {reviews: review._id}}).exec(),
]).then(function() {
req.flash('messages', {
style: 'success',
type: 'Success',
text: 'Your review has been submitted!',
});
res.redirect('/applications');
}, function(err) {
req.flash('messages', {
style: 'danger',
type: 'Error',
text: 'Something went wrong submitting the application!',
});
res.redirect('/applications');
})
});
}
Alternative solution code:
req.body.reviwer = req.user.id;
req.body.application = req.params.applicationId;
Review.create(req.body).then(...)
Upvotes: 0
Views: 95
Reputation: 25034
From what I understand you are making two mistakes:
return
in front of Q.all
else, it would just assume return null
i.e won't wait till Q.all is finishedQ.all
is a function, I am pretty sure that it has to be a promise,I have placed the function details outside, hope it works now:
...
Review.create(req.body).then(function(review) {
review.reviewer = req.user.id;
review.application = req.params.applicationId;
return Q.all([
review.save(),
User.findByIdAndUpdate(review.reviewer, {$push: {reviews: review._id}}).exec(),
Application.findByIdAndUpdate(review.application, {$push: {reviews: review._id}}).exec(),
]).then(function() {
...
Upvotes: 3