---
title: "Comment by Benjamin J on \"Are you using map, forEach, and reduce wrong?\" | Hashnode"
description: "Interesting article. A friendly heads up that I think there&#39;s a subtle race condition in your getArticleTypeById . It loads in everything from article_types"
url: "https://hashnode.com/posts/are-you-using-map-foreach-and-reduce-wrong/6236f5328e4fae3f767de87c/comment/6538bef0c6b0d16a577016f5"
---

[Discussion](https://hashnode.com/posts/are-you-using-map-foreach-and-reduce-wrong/6236f5328e4fae3f767de87c)

Comment [Are you using map, forEach, and reduce wrong?](https://hashnode.com/posts/are-you-using-map-foreach-and-reduce-wrong/6236f5328e4fae3f767de87c)

[Benjamin J](https://hashnode.com/@benj123)

[Oct 25, 2023](https://hashnode.com/posts/are-you-using-map-foreach-and-reduce-wrong/6236f5328e4fae3f767de87c/comment/6538bef0c6b0d16a577016f5)

Interesting article.

A friendly heads up that I think there's a subtle race condition in your `getArticleTypeById`. It loads in everything from `article_types`, but it is invoked by `map` -- so it could be called many times in close succession.

The problem is that the `cache` local variable is set only after querying `article_types`, so this means that it's possible to have multiple Postgres queries outstanding. I suppose you're using a pool, so the impact will be limited by the pool size. However, it would mean that the entire pool could be temporarily exhausted before the cache is built and set.

Perhaps one way to fix it would be to make cache a `Promise<Map<...>>` instead of just a `Map<...>`. Something like this:

```
const buildCache = async () => {....};
if (!cache) {
  // note: no await here - we want the promise
  cache = buildCache(); 
}
return (await cache).get(id);
```

There's something similar in your Outbox pattern blog post too - awaiting on `connect()` between checking the `CURSOR_REPO_MAP` and updating the `CURSOR_REPO_MAP`, so not 100% guaranteeing a singleton.
