2 const pLimit = require('p-limit');
4 class EndError extends Error {
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])));
14 module.exports = (iterable, tester, opts) => {
15 opts = Object.assign({
16 concurrency: Infinity,
20 const limit = pLimit(opts.concurrency);
22 // start all the promises concurrently with optional limit
23 const items = Array.from(iterable).map(el => [el, limit(() => Promise.resolve(el).then(tester))]);
25 // check the promises either serially or concurrently
26 const checkLimit = pLimit(opts.preserveOrder ? 1 : Infinity);
28 return Promise.all(items.map(el => checkLimit(() => finder(el))))
30 .catch(err => err instanceof EndError ? err.value : Promise.reject(err));