Skip to content

asyncForEachFields

输入一个对象obj和迭代器iterator,遍历对象的每个字段,对每个字段的值执行iterator

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

Added in v0.0.1

Usage

ts
import { asyncForEachFields } from 'parsnip-kit'

const obj = { a: 1, b: 2, c: 3 }

const logConcurrent = [] as any[]
const iterator = (value, key, object) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      logConcurrent.push({ key, value })
      resolve(void 0)
    }, Math.random() * 100)
  })
}
asyncForEachFields(obj, iterator, 'sequential').then(() => {
  console.log(logConcurrent)
  // Array contain { key: 'a', value: 1 }, { key: 'b', value: 2 }, { key: 'c', value: 3 } with random order.
})

const logSequential = [] as any[]
const iterator = (value, key, object) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      logSequential.push({ key, value })
      resolve(void 0)
    }, Math.random() * 100)
  })
}
asyncForEachFields(obj, iterator, 'sequential').then(() => {
  console.log(logSequential)
  // [{ key: 'a', value: 1 }, { key: 'b', value: 2 }, { key: 'c', value: 3 }]
})

API

Type Parameter

ArgTypeDescription
Textends object对象类型
Rextends 'concurrent' | 'sequential' = 'concurrent' | 'sequential'并发类型

Arguments

ArgTypeOptionalDefaultDescription
objTfalseundefined待遍历的对象
iterator(value: any, key: string, object: T) => anyfalseundefined迭代器函数
concurrentRtrue'concurrent'并发类型

Returns

Type
Promise<void>