index.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334
  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.resolve()` it
  10. const testElement = (el, tester) => Promise.resolve(el).then(tester);
  11. // The input can also be a promise, so we `Promise.all()` them both
  12. const finder = el => Promise.all(el).then(val => val[1] === true && Promise.reject(new EndError(val[0])));
  13. module.exports = (iterable, tester, opts) => {
  14. opts = Object.assign({
  15. concurrency: Infinity,
  16. preserveOrder: true
  17. }, opts);
  18. const limit = pLimit(opts.concurrency);
  19. // Start all the promises concurrently with optional limit
  20. const items = [...iterable].map(el => [el, limit(testElement, el, tester)]);
  21. // Check the promises either serially or concurrently
  22. const checkLimit = pLimit(opts.preserveOrder ? 1 : Infinity);
  23. return Promise.all(items.map(el => checkLimit(finder, el)))
  24. .then(() => {})
  25. .catch(err => err instanceof EndError ? err.value : Promise.reject(err));
  26. };