Open2

neverthrowで配列の要素に非同期関数を直列に適用するユーティリティ関数

Nakano as a ServiceNakano as a Service

neverthrowで配列に対してmapをsequentialに適用するユーティリティ関数。

import type { Err, ResultAsync, Result } from 'neverthrow';
import { fromSafePromise, ok } from 'neverthrow';

async function seqMapPromise<T, U, E>(
  arr: T[],
  callback: (e: T) => ResultAsync<U, E>
): Promise<Result<U[], E>> {
  const results: U[] = [];
  for (const e of arr) {
    const result = await callback(e);
    if (result.isErr()) {
      return result as Err<U[], E>;
    }
    results.push(result.value);
  }
  return ok(results);
}

export function seqMap<T, U, E>(
  arr: T[],
  callback: (e: T) => ResultAsync<U, E>
): ResultAsync<U[], E> {
  return fromSafePromise(seqMapPromise(arr, callback)).andThen((e) => e);
}