I have been exploring Promises
for a while in JavaScript and thought of getting better at it.
I made a small blog app in Node. The scenario is whenever a user is deleted I want to delete all the blogs created by the user and also remove the user from the likes
of the blog.
Below is the code for it.
const user = req.user;
console.log(user);
// Finding the blogs created by the user and creating an array of promises
const createdBlogs = await Blog.find({creator: user._id});
const createdBlogsPromises = createdBlogs.map(async blog => await Blog.findByIdAndDelete(blog._id));
// Finding the blogs liked by the user and creating an array of promises
// removeUser is an instance method in blogSchema
const likedBlogs = await Blog.find({likes: {$in: user._id}});
const likedBlogsPromises = likedBlogs.map(async blog => await blog.removeUser(user));
// Using all method for parallel execution of promises
const promiseResponse = await Promise.all([...createdBlogsPromises, ...likedBlogsPromises]);
console.log(promiseResponse);
await User.deleteOne({_id: user._id});
res.status(204).json({message: 'Successfully deleted!!'});
I am using Promise.all()
for this. Is this the right way to use Promise.all()
or is there an alternative and easy way to perform this ?