index.d.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. declare namespace pMap {
  2. interface Options {
  3. /**
  4. Number of concurrently pending promises returned by `mapper`.
  5. Must be an integer from 1 and up or `Infinity`.
  6. @default Infinity
  7. */
  8. readonly concurrency?: number;
  9. /**
  10. 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.
  11. @default true
  12. */
  13. readonly stopOnError?: boolean;
  14. }
  15. /**
  16. Function which is called for every item in `input`. Expected to return a `Promise` or value.
  17. @param element - Iterated element.
  18. @param index - Index of the element in the source array.
  19. */
  20. type Mapper<Element = any, NewElement = unknown> = (
  21. element: Element,
  22. index: number
  23. ) => NewElement | Promise<NewElement>;
  24. }
  25. /**
  26. @param input - Iterated over concurrently in the `mapper` function.
  27. @param mapper - Function which is called for every item in `input`. Expected to return a `Promise` or value.
  28. @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.
  29. @example
  30. ```
  31. import pMap = require('p-map');
  32. import got = require('got');
  33. const sites = [
  34. getWebsiteFromUsername('https://sindresorhus'), //=> Promise
  35. 'https://ava.li',
  36. 'https://github.com'
  37. ];
  38. (async () => {
  39. const mapper = async site => {
  40. const {requestUrl} = await got.head(site);
  41. return requestUrl;
  42. };
  43. const result = await pMap(sites, mapper, {concurrency: 2});
  44. console.log(result);
  45. //=> ['https://sindresorhus.com/', 'https://ava.li/', 'https://github.com/']
  46. })();
  47. ```
  48. */
  49. declare function pMap<Element, NewElement>(
  50. input: Iterable<Element>,
  51. mapper: pMap.Mapper<Element, NewElement>,
  52. options?: pMap.Options
  53. ): Promise<NewElement[]>;
  54. export = pMap;