This is node.js with Mongoose and Bluebird required already.
I have, without promises, the following:
Post.create({
title: "How to cook the best burger pt 4",
content: "Mustard!"
}, (err,post) => {
console.log(post);
User.findOne({name: 'Bob Belcher'}, (err,user) => {
console.log('found user')
user.posts.push(post)
user.save((err,data) => {
console.log(data)
})
})
})
Which I'd like to convert to using Promises. My attempt (which does not work) is as follows:
var postPromise = Post.create({
title: "How to cook the best burger pt 4",
content: "Mustard!"
}
postPromise
.then((post) => {
return User.findOne({'name': 'Bob Belcher'}).exec()
}
.then((user) => {
user.posts.push(post) // <--- this post was within the scope of previous thenable hence inaccessible here
return user.save()
})
.catch((err) => {
console.log(err)
})
Problem is I'm not sure how to pass the 'post' from the 'post' promise clause, on to the 'user' thenable so that I can actually insert it in to the database. With callback hell, everything was nested so all the parent variables are within scope and easily accessible. I'm still trying to map my brain to thinking in the promises 'way'. I hope this was clear enough. Thanks.