Skip to content

asyncMap

输入一个数组array和迭代器iterator,遍历对象的每个元素,对每个元素执行iterator,并返回由每次await执行后的返回值组成的数组。

iterator支持async函数,或者Promise返回值。concurrent可选参数控制是否并发调用,若值为'sequential',当前一个iterator返回的Promise为 fulfilled 或者 rejected 后,才会执行新的iterator

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
T数组元素类型
Uiterator返回值类型
Rextends 'concurrent' | 'sequential' = 'concurrent' | 'sequential'并发类型

Arguments

ArgTypeOptionalDefaultDescription
arrayT[]falseundefined待遍历的数组
iterator(item: T, index: number, array: T[]) => U | Promise<U>falseundefined迭代器函数
concurrentRtrue'concurrent'并发类型

Returns

Type
Promise<U[]>