UNPKG

2.59 kBTypeScriptView Raw
1export interface Options {
2 /**
3 Number of concurrently pending promises returned by `mapper`.
4
5 Must be an integer from 1 and up or `Infinity`.
6
7 @default Infinity
8 */
9 readonly concurrency?: number;
10
11 /**
12 When set to `false`, instead of stopping when a promise rejects, it will wait for all the promises to settle and then reject with an [aggregated error](https://github.com/sindresorhus/aggregate-error) containing all the errors from the rejected promises.
13
14 @default true
15 */
16 readonly stopOnError?: boolean;
17}
18
19/**
20Function which is called for every item in `input`. Expected to return a `Promise` or value.
21
22@param element - Iterated element.
23@param index - Index of the element in the source array.
24*/
25export type Mapper<Element = any, NewElement = unknown> = (
26 element: Element,
27 index: number
28) => NewElement | Promise<NewElement>;
29
30/**
31@param input - Iterated over concurrently in the `mapper` function.
32@param mapper - Function which is called for every item in `input`. Expected to return a `Promise` or value.
33@returns A `Promise` that is fulfilled when all promises in `input` and ones returned from `mapper` are fulfilled, or rejects if any of the promises reject. The fulfilled value is an `Array` of the fulfilled values returned from `mapper` in `input` order.
34
35@example
36```
37import pMap from 'p-map';
38import got from 'got';
39
40const sites = [
41 getWebsiteFromUsername('sindresorhus'), //=> Promise
42 'https://avajs.dev',
43 'https://github.com'
44];
45
46const mapper = async site => {
47 const {requestUrl} = await got.head(site);
48 return requestUrl;
49};
50
51const result = await pMap(sites, mapper, {concurrency: 2});
52
53console.log(result);
54//=> ['https://sindresorhus.com/', 'https://avajs.dev/', 'https://github.com/']
55```
56*/
57export default function pMap<Element, NewElement>(
58 input: Iterable<Element>,
59 mapper: Mapper<Element, NewElement>,
60 options?: Options
61): Promise<Array<Exclude<NewElement, typeof pMapSkip>>>;
62
63/**
64Return this value from a `mapper` function to skip including the value in the returned array.
65
66@example
67```
68import pMap, {pMapSkip} from 'p-map';
69import got from 'got';
70
71const sites = [
72 getWebsiteFromUsername('sindresorhus'), //=> Promise
73 'https://avajs.dev',
74 'https://example.invalid',
75 'https://github.com'
76];
77
78const mapper = async site => {
79 try {
80 const {requestUrl} = await got.head(site);
81 return requestUrl;
82 } catch {
83 return pMapSkip
84 }
85};
86
87const result = await pMap(sites, mapper, {concurrency: 2});
88
89console.log(result);
90//=> ['https://sindresorhus.com/', 'https://avajs.dev/', 'https://github.com/']
91```
92*/
93export const pMapSkip: unique symbol;