Created
May 23, 2019 16:10
-
-
Save kevivforever/efa1e4099fff42b7ce27a1abb3f088ac to your computer and use it in GitHub Desktop.
How to write async await
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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