You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
2.2 KiB

4 years ago
  1. # p-map [![Build Status](https://travis-ci.org/sindresorhus/p-map.svg?branch=master)](https://travis-ci.org/sindresorhus/p-map)
  2. > Map over promises concurrently
  3. Useful when you need to run promise-returning & async functions multiple times with different inputs concurrently.
  4. ## Install
  5. ```
  6. $ npm install p-map
  7. ```
  8. ## Usage
  9. ```js
  10. const pMap = require('p-map');
  11. const got = require('got');
  12. const sites = [
  13. getWebsiteFromUsername('sindresorhus'), //=> Promise
  14. 'ava.li',
  15. 'todomvc.com',
  16. 'github.com'
  17. ];
  18. (async () => {
  19. const mapper = async site => {
  20. const {requestUrl} = await got.head(site);
  21. return requestUrl;
  22. };
  23. const result = await pMap(sites, mapper, {concurrency: 2});
  24. console.log(result);
  25. //=> ['http://sindresorhus.com/', 'http://ava.li/', 'http://todomvc.com/', 'http://github.com/']
  26. })();
  27. ```
  28. ## API
  29. ### pMap(input, mapper, [options])
  30. 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.
  31. #### input
  32. Type: `Iterable<Promise|any>`
  33. Iterated over concurrently in the `mapper` function.
  34. #### mapper(element, index)
  35. Type: `Function`
  36. Expected to return a `Promise` or value.
  37. #### options
  38. Type: `Object`
  39. ##### concurrency
  40. Type: `number`<br>
  41. Default: `Infinity`<br>
  42. Minimum: `1`
  43. Number of concurrently pending promises returned by `mapper`.
  44. ## Related
  45. - [p-all](https://github.com/sindresorhus/p-all) - Run promise-returning & async functions concurrently with optional limited concurrency
  46. - [p-filter](https://github.com/sindresorhus/p-filter) - Filter promises concurrently
  47. - [p-times](https://github.com/sindresorhus/p-times) - Run promise-returning & async functions a specific number of times concurrently
  48. - [p-props](https://github.com/sindresorhus/p-props) - Like `Promise.all()` but for `Map` and `Object`
  49. - [p-map-series](https://github.com/sindresorhus/p-map-series) - Map over promises serially
  50. - [p-queue](https://github.com/sindresorhus/p-queue) - Promise queue with concurrency control
  51. - [More…](https://github.com/sindresorhus/promise-fun)
  52. ## License
  53. MIT © [Sindre Sorhus](https://sindresorhus.com)