UNPKG

2.4 kBMarkdownView Raw
1# p-locate
2
3> Get the first fulfilled promise that satisfies the provided testing function
4
5Think of it like an async version of [`Array#find`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find).
6
7## Install
8
9```
10$ npm install p-locate
11```
12
13## Usage
14
15Here we find the first file that exists on disk, in array order.
16
17```js
18import {pathExists} from 'path-exists';
19import pLocate from 'p-locate';
20
21const files = [
22 'unicorn.png',
23 'rainbow.png', // Only this one actually exists on disk
24 'pony.png'
25];
26
27const foundPath = await pLocate(files, file => pathExists(file));
28
29console.log(foundPath);
30//=> 'rainbow'
31```
32
33*The above is just an example. Use [`locate-path`](https://github.com/sindresorhus/locate-path) if you need this.*
34
35## API
36
37### pLocate(input, tester, options?)
38
39Returns a `Promise` that is fulfilled when `tester` resolves to `true` or the iterable is done, or rejects if any of the promises reject. The fulfilled value is the current iterable value or `undefined` if `tester` never resolved to `true`.
40
41#### input
42
43Type: `Iterable<Promise | unknown>`
44
45An iterable of promises/values to test.
46
47#### tester(element)
48
49Type: `Function`
50
51This function will receive resolved values from `input` and is expected to return a `Promise<boolean>` or `boolean`.
52
53#### options
54
55Type: `object`
56
57##### concurrency
58
59Type: `number`\
60Default: `Infinity`\
61Minimum: `1`
62
63The number of concurrently pending promises returned by `tester`.
64
65##### preserveOrder
66
67Type: `boolean`\
68Default: `true`
69
70Preserve `input` order when searching.
71
72Disable this to improve performance if you don't care about the order.
73
74## Related
75
76- [p-map](https://github.com/sindresorhus/p-map) - Map over promises concurrently
77- [p-filter](https://github.com/sindresorhus/p-filter) - Filter promises concurrently
78- [p-any](https://github.com/sindresorhus/p-any) - Wait for any promise to be fulfilled
79- [More…](https://github.com/sindresorhus/promise-fun)
80
81---
82
83<div align="center">
84 <b>
85 <a href="https://tidelift.com/subscription/pkg/npm-p-locate?utm_source=npm-p-locate&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
86 </b>
87 <br>
88 <sub>
89 Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
90 </sub>
91</div>