const Like = {
find: () => ({
countDocuments: async () =>
new Promise((resolve) => setTimeout(() => resolve(123), 100)),
}),
};
const article = {
_id: 1,
comments: [{ _id: 1 }, { _id: 1 }, { _id: 1 }, { _id: 1 }],
};
Promise.all(
article.comments.map(async (item) => {
const newItem = { ...item };
newItem.likes = await Like.find({
article: article._id,
comment: item._id,
type: "like",
}).countDocuments();
newItem.dislikes = await Like.find({
article: article._id,
comment: item._id,
type: "dislike",
}).countDocuments();
return newItem;
})
).then(() => deferred.resolve());
Promise.all(
article.comments.map((item) =>
Promise.all([
Like.find({
article: article._id,
comment: item._id,
type: "like",
}).countDocuments(),
Like.find({
article: article._id,
comment: item._id,
type: "dislike",
}).countDocuments(),
]).then(([likes, dislikes]) => ({
...item,
likes,
dislikes,
}))
)
).then(() => deferred.resolve());
Promise.all(
article.comments.map(async (item) => {
const [likes, dislikes] = await Promise.all([
Like.find({
article: article._id,
comment: item._id,
type: "like",
}).countDocuments(),
Like.find({
article: article._id,
comment: item._id,
type: "dislike",
}).countDocuments(),
]);
return {
likes,
dislikes,
...item,
};
})
).then(() => deferred.resolve());