Skip to content

Instantly share code, notes, and snippets.

@nullmastermind
Last active May 4, 2024 19:58
Show Gist options
  • Save nullmastermind/965bdfb8a1b98fda6432a2e34b05da76 to your computer and use it in GitHub Desktop.
Save nullmastermind/965bdfb8a1b98fda6432a2e34b05da76 to your computer and use it in GitHub Desktop.
Lodash async forEach implementation
import { map } from 'lodash';
async function asyncForEach<T>(
items: Array<T> | null | undefined,
iter: (v: T, k: number) => Promise<boolean | void>,
): Promise<void>;
async function asyncForEach<T, K extends string>(
items: Record<K, T> | null | undefined,
iter: (v: T, k: K) => Promise<boolean | void>,
): Promise<void>;
async function asyncForEach<T, K extends number | string>(
items: Array<T> | Record<K, T> | null | undefined,
iter: (v: T, k: K) => Promise<boolean | void>,
) {
const kvItems = map(items, (value, index) => ({
v: value as T,
k: index as K,
}));
for (const kvItem of kvItems) {
if ((await iter(kvItem.v, kvItem.k)) === false) break;
}
}
export default asyncForEach;
@nullmastermind
Copy link
Author

import asyncForEach from '@/utils/asyncForEach/asyncForEach';
import { sleep } from '@/utils/common';

async function main() {
  await asyncForEach(
    {
      a: 1,
      b: '2',
    },
    async (v, k) => {
      console.log(`${k}: ${v}`);
      await sleep(1000);
      return false;
    },
  );
}

void main();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment