Skip to content

asyncForEach

输入一个数组array和迭代器iterator,遍历对象的每个元素,对每个元素执行iterator

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

Added in v0.0.1

Usage

ts
import { asyncForEach } 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(void 0)
    }, Math.random() * 100)
  })
}
asyncForEach(array, iterator).then(() => {
  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(void 0)
    }, Math.random() * 100)
  })
}
asyncForEach(array, iterator, 'sequential').then(() => {
  console.log(logSequential)
  // [{ item: 1, index: 0 }, { item: 2, index: 1 }, { item: 3, index: 2 }]
})

API

Type Parameter

ArgTypeDescription
T数组元素类型
Rextends 'concurrent' | 'sequential' = 'concurrent' | 'sequential'并发类型

Arguments

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

Returns

Type
Promise<void>