Skip to content

Instantly share code, notes, and snippets.

@manderly
Created June 6, 2020 19:01
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 manderly/1a1cd9a0e77cc5a9e072d6885af70ffd to your computer and use it in GitHub Desktop.
Save manderly/1a1cd9a0e77cc5a9e072d6885af70ffd to your computer and use it in GitHub Desktop.
let allPosts = [ {id: 123, name: "test post 1"},
{id: 456, name: "test post 2"}
];
let allReplies = [ {id: 1, replyTo: 123, name: 'reply 1', read: false},
{id: 2, replyTo: 123, name: 'reply 2', read: false},
{id: 3, replyTo: 456, name: 'reply 3', read: false}
];
// simulate a server response with 1s wait time
const getRepliesToPost = async (id: number) => {
let replies = [];
for (let i = 0; i < 10; i++) {
const reply = new Promise((resolve, reject) => {
if (allReplies[i] && allReplies[i].replyTo === id) {
resolve(allReplies[i]);
} else {
reject('reply not found');
}
});
replies.push(reply);
}
return replies;
}
const processUnreadReplies = async(posts: any) => {
let repliesTotal = 0;
for (let post of posts) {
const replyArray: Array<any> = await getRepliesToPost(post.id);
replyArray.forEach(async (reply: any) => {
const resolved = await reply;
if (!resolved.read) {
post.unreadReplyCount = (post.unreadReplyCount ?? 0) + 1;
repliesTotal++;
}
});
};
console.log(repliesTotal);
}
processUnreadReplies(allPosts); // logs 2 (good)
// guarantees an order, whereas forEach does not
const processUnreadRepliesWithForOf = async (posts: any) => {
let repliesTotal = 0;
for (let post of posts) {
const replyArray: Array<any> = await getRepliesToPost(post.id);
for await (let reply of replyArray) {
if (!reply.read) {
post.unreadReplyCount = (post.unreadReplyCount ?? 0) + 1;
repliesTotal++;
}
repliesTotal
}
}
console.log(repliesTotal);
}
processUnreadRepliesWithForOf(allPosts); // logs 20 (bad)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment