Concurrency
mapAsync

⚡ Asynchronous version of `Array.prototype.map`.

By default, it runs all iterations in parallel. You can limit the concurrency by providing a third argument.

Syntax

import { mapAsync } from '@opentf/std';
 
mapAsync<T, R>(
  arr: T[],
  cb: (value: T, index: number) => Promise<R>,
  concurrency?: number
): Promise<R[]>;

Parameters

  • arr: The array to iterate over.
  • cb: An async callback function for each element.
  • concurrency (Optional): The maximum number of concurrent executions. Default: Infinity.

Returns

A Promise that resolves to the new mapped array.

Examples

Parallel Execution (Default)

const items = [1, 2, 3];
await mapAsync(items, async (n) => {
  return n * 2;
}); //=> [2, 4, 6]

Sequential Execution

Set concurrency to 1 to run tasks one after another.

const items = [1, 2, 3];
await mapAsync(
  items,
  async (n) => {
    return n * 2;
  },
  1
); //=> [2, 4, 6]

Related

Try