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.

readme.md 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # p-reduce [![Build Status](https://travis-ci.org/sindresorhus/p-reduce.svg?branch=master)](https://travis-ci.org/sindresorhus/p-reduce)
  2. > Reduce a list of values using promises into a promise for a value
  3. Useful when you need to calculate some accumulated value based on async resources.
  4. ## Install
  5. ```
  6. $ npm install --save p-reduce
  7. ```
  8. ## Usage
  9. ```js
  10. const pReduce = require('p-reduce');
  11. const humanInfo = require('human-info'); // not a real module
  12. const names = [
  13. getUser('sindresorhus').then(info => info.name),
  14. 'Addy Osmani',
  15. 'Pascal Hartig',
  16. 'Stephen Sawchuk'
  17. ];
  18. pReduce(names, (total, name) => {
  19. return humanInfo(name).then(info => total + info.age);
  20. }, 0).then(totalAge => {
  21. console.log(totalAge);
  22. //=> 125
  23. });
  24. ```
  25. ## API
  26. ### pReduce(input, reducer, [initialValue])
  27. Returns a `Promise` that is fulfilled when all promises in `input` and ones returned from `reducer` are fulfilled, or rejects if any of the promises reject. The fulfilled value is the result of the reduction.
  28. #### input
  29. Type: `Iterable<Promise|any>`
  30. Iterated over serially in the `reducer` function.
  31. #### reducer(previousValue, currentValue, index)
  32. Type: `Function`
  33. Expected to return a value. If a `Promise` is returned, it's awaited before continuing with the next iteration.
  34. #### initialValue
  35. Type: `any`
  36. Value to use as `previousValue` in the first `reducer` invocation.
  37. ## Related
  38. - [p-each-series](https://github.com/sindresorhus/p-each-series) - Iterate over promises serially
  39. - [p-map-series](https://github.com/sindresorhus/p-map-series) - Map over promises serially
  40. - [p-map](https://github.com/sindresorhus/p-map) - Map over promises concurrently
  41. - [More…](https://github.com/sindresorhus/promise-fun)
  42. ## License
  43. MIT © [Sindre Sorhus](https://sindresorhus.com)