Skip to content

asyncMap

Input an array array and an iterator iterator, traverse each element of the array, execute the iterator on each element, and return an array composed of the return values after each execution using await.

The iterator supports async functions or functions that return a Promise. The optional parameter concurrent controls whether the iterator functions are called concurrently. If the value is 'sequential', the next iterator will only be executed after the Promise returned by the previous iterator is either fulfilled or rejected.

Added in v0.0.1

Usage

ts
import { asyncMap } from 'parsnip-kit'

const array = [1, 2, 3]
const logConcurrent = [] as any[]
const iterator = (item, index, arr) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      logConcurrent.push({ item, index })
      resolve({ item, index })
    }, Math.random() * 100)
  })
}
asyncMap(array, iterator).then(res => {
  console.log(res)
  // [{ item: 1, index: 0 }, { item: 2, index: 1 }, { item: 3, index: 2 }]
  console.log(logConcurrent)
  // Array contain { item: 1, index: 0 }, { item: 2, index: 1 }, { item: 3, index: 2 } with random order.
})

const logSequential = [] as any[]
const iterator = (item, index, arr) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      logSequential.push({ item, index })
      resolve({ item, index })
    }, Math.random() * 100)
  })
}
asyncMap(array, iterator, 'sequential').then(res => {
  console.log(res)
  // [{ item: 1, index: 0 }, { item: 2, index: 1 }, { item: 3, index: 2 }]
  console.log(logSequential)
  // [{ item: 1, index: 0 }, { item: 2, index: 1 }, { item: 3, index: 2 }]
})

API

Type Parameter

ArgTypeDescription
TElement type of array
UReturn type of the iterator
Rextends 'concurrent' | 'sequential' = 'concurrent' | 'sequential'Concurrent type

Arguments

ArgTypeOptionalDefaultDescription
arrayT[]falseundefinedArray to iterate
iterator(item: T, index: number, array: T[]) => U | Promise<U>falseundefinedIterator function
concurrentRtrue'concurrent'Concurrent type

Returns

Type
Promise<U[]>