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
Arg | Type | Description |
---|---|---|
T |
| 数组元素类型 |
R | extends 'concurrent' | 'sequential' = 'concurrent' | 'sequential' | 并发类型 |
Arguments
Arg | Type | Optional | Default | Description |
---|---|---|---|---|
array | T[] | false | undefined | 待遍历的数组 |
iterator | (item: T, index: number, array: T[]) => any | false | undefined | 迭代器函数 |
concurrent | R | true | 'concurrent' | 并发类型 |
Returns
Type |
---|
Promise<void> |