(items: undefined | Iterable<T> | Promise<Iterable<T> | undefined> | Promise<undefined> | AsyncIterable<T> | Promise<AsyncIterable<T>>, predicate: (item: T) => Promise<TResult>)
| 9 | |
| 10 | /** an async foreach function to iterate over any iterable/async iterable, calling a function on each item in parallel as possible */ |
| 11 | export async function foreach<T, TResult>(items: undefined | Iterable<T> | Promise<Iterable<T> | undefined> | Promise<undefined> | AsyncIterable<T> | Promise<AsyncIterable<T>>, predicate: (item: T) => Promise<TResult>): Promise<TResult[]> { |
| 12 | items = is.promise(items) ? await items : items; // unwrap the promise if it is one |
| 13 | |
| 14 | if (items) { |
| 15 | const result = [] as Promise<TResult>[]; |
| 16 | if (is.asyncIterable(items)) { |
| 17 | for await (const item of items) { |
| 18 | result.push(predicate(item)); // run the predicate on each item |
| 19 | } |
| 20 | } else { |
| 21 | for (const item of items) { |
| 22 | result.push(predicate(item)); // run the predicate on each item |
| 23 | } |
| 24 | } |
| 25 | return Promise.all(result); |
| 26 | } |
| 27 | return []; // return an empty array if there is nothing to iterate over |
| 28 | } |
| 29 | |
| 30 | interface Cursor<T> { |
| 31 | identity: number; |
no test coverage detected