index.js 934 B

12345678910111213141516171819202122232425262728293031
  1. 'use strict';
  2. const pLimit = require('p-limit');
  3. class EndError extends Error {
  4. constructor(value) {
  5. super();
  6. this.value = value;
  7. }
  8. }
  9. // the input can also be a promise, so we `Promise.all()` them both
  10. const finder = el => Promise.all(el).then(val => val[1] === true && Promise.reject(new EndError(val[0])));
  11. module.exports = (iterable, tester, opts) => {
  12. opts = Object.assign({
  13. concurrency: Infinity,
  14. preserveOrder: true
  15. }, opts);
  16. const limit = pLimit(opts.concurrency);
  17. // start all the promises concurrently with optional limit
  18. const items = Array.from(iterable).map(el => [el, limit(() => Promise.resolve(el).then(tester))]);
  19. // check the promises either serially or concurrently
  20. const checkLimit = pLimit(opts.preserveOrder ? 1 : Infinity);
  21. return Promise.all(items.map(el => checkLimit(() => finder(el))))
  22. .then(() => {})
  23. .catch(err => err instanceof EndError ? err.value : Promise.reject(err));
  24. };