p-locate
Advanced tools
Comparing version 1.0.0 to 2.0.0
27
index.js
'use strict'; | ||
const pMap = require('p-map'); | ||
const pLimit = require('p-limit'); | ||
@@ -11,9 +11,22 @@ class EndError extends Error { | ||
module.exports = (iterable, tester, opts) => | ||
pMap(iterable, el => ( | ||
Promise.resolve() | ||
.then(() => tester(el)) | ||
.then(val => val === true && Promise.reject(new EndError(el))) | ||
), opts) | ||
// the input can also be a promise, so we `Promise.all()` them both | ||
const finder = el => Promise.all(el).then(val => val[1] === true && Promise.reject(new EndError(val[0]))); | ||
module.exports = (iterable, tester, opts) => { | ||
opts = Object.assign({ | ||
concurrency: Infinity, | ||
preserveOrder: true | ||
}, opts); | ||
const limit = pLimit(opts.concurrency); | ||
// start all the promises concurrently with optional limit | ||
const items = Array.from(iterable).map(el => [el, limit(() => Promise.resolve(el).then(tester))]); | ||
// check the promises either serially or concurrently | ||
const checkLimit = pLimit(opts.preserveOrder ? 1 : Infinity); | ||
return Promise.all(items.map(el => checkLimit(() => finder(el)))) | ||
.then(() => {}) | ||
.catch(err => err instanceof EndError ? err.value : Promise.reject(err)); | ||
}; |
{ | ||
"name": "p-locate", | ||
"version": "1.0.0", | ||
"version": "2.0.0", | ||
"description": "Get the first fulfilled promise that satisfies the provided testing function", | ||
@@ -42,3 +42,3 @@ "license": "MIT", | ||
"dependencies": { | ||
"p-map": "^1.1.0" | ||
"p-limit": "^1.1.0" | ||
}, | ||
@@ -45,0 +45,0 @@ "devDependencies": { |
@@ -25,7 +25,10 @@ # p-locate [![Build Status](https://travis-ci.org/sindresorhus/p-locate.svg?branch=master)](https://travis-ci.org/sindresorhus/p-locate) | ||
'unicorn.png', | ||
'rainbow.png', | ||
getUserSpecifiedPath() //=> Promise | ||
'rainbow.png', // only this one actually exists on disk | ||
'pony.png' | ||
]; | ||
pLocate(files, file => pathExists(file), {concurrency: 1}); | ||
pLocate(files, file => pathExists(file)).then(foundPath => { | ||
console.log(foundPath); | ||
//=> 'rainbow' | ||
}); | ||
``` | ||
@@ -46,4 +49,2 @@ | ||
Set `{concurrency: 1}` to preserve the search order. | ||
#### tester(element) | ||
@@ -67,3 +68,12 @@ | ||
##### preserveOrder | ||
Type: `boolean`<br> | ||
Default: `true` | ||
Preserve `input` order when searching. | ||
Disable this to improve performance if you don't care about the order. | ||
## Related | ||
@@ -70,0 +80,0 @@ |
5053
24
87
+ Addedp-limit@^1.1.0
+ Addedp-limit@1.3.0(transitive)
+ Addedp-try@1.0.0(transitive)
- Removedp-map@^1.1.0
- Removedp-map@1.2.0(transitive)