2 const pLimit = require('p-limit');
4 class EndError extends Error {
11 // The input can also be a promise, so we await it
12 const testElement = async (element, tester) => tester(await element);
14 // The input can also be a promise, so we `Promise.all()` them both
15 const finder = async element => {
16 const values = await Promise.all(element);
17 if (values[1] === true) {
18 throw new EndError(values[0]);
24 const pLocate = async (iterable, tester, options) => {
26 concurrency: Infinity,
31 const limit = pLimit(options.concurrency);
33 // Start all the promises concurrently with optional limit
34 const items = [...iterable].map(element => [element, limit(testElement, element, tester)]);
36 // Check the promises either serially or concurrently
37 const checkLimit = pLimit(options.preserveOrder ? 1 : Infinity);
40 await Promise.all(items.map(element => checkLimit(finder, element)));
42 if (error instanceof EndError) {
50 module.exports = pLocate;
51 // TODO: Remove this for the next major release
52 module.exports.default = pLocate;