Skip to content

Instantly share code, notes, and snippets.

@kevivforever
Created May 23, 2019 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevivforever/efa1e4099fff42b7ce27a1abb3f088ac to your computer and use it in GitHub Desktop.
Save kevivforever/efa1e4099fff42b7ce27a1abb3f088ac to your computer and use it in GitHub Desktop.
How to write async await
async function addInterestedCategories(uid, categories) {
await User.findOneAndUpdate({ uid: uid },
{ $addToSet: { interested_categories: categories } }, { new: true}).exec()
}
exports.getPost = async (req, res, next) => {
const postUpdate = await Post.findOneAndUpdate({ postID: req.params.postid
, viewedBy: { $not: { $elemMatch: { uid: req.query.uid } } }
},
{ $addToSet: { viewedBy: USER }, $inc: { totalViews: 1} }, { new: true })
.exec()
const countUpdate = await addViewCount(req.query.uid, posts[0].uid, req.params.postid)
const categoryupdate = await addInterestedCategories(req.query.uid, posts[0].categories)
// response will be sent when all promises are resolved
Promise.all([countUpdate, categoryupdate, postUpdate]).then(() => {
console.log("request complete")
res.status(200).json(commonController.moderatePost(posts[0]));
})
// if you want to execute the task asynchronously
await addInterestedCategories(req.query.uid, posts[0].categories)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment