1 | # p-locate
|
2 |
|
3 | > Get the first fulfilled promise that satisfies the provided testing function
|
4 |
|
5 | Think 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 |
|
15 | Here we find the first file that exists on disk, in array order.
|
16 |
|
17 | ```js
|
18 | import {pathExists} from 'path-exists';
|
19 | import pLocate from 'p-locate';
|
20 |
|
21 | const files = [
|
22 | 'unicorn.png',
|
23 | 'rainbow.png', // Only this one actually exists on disk
|
24 | 'pony.png'
|
25 | ];
|
26 |
|
27 | const foundPath = await pLocate(files, file => pathExists(file));
|
28 |
|
29 | console.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 |
|
39 | Returns 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 |
|
43 | Type: `Iterable<Promise | unknown>`
|
44 |
|
45 | An iterable of promises/values to test.
|
46 |
|
47 | #### tester(element)
|
48 |
|
49 | Type: `Function`
|
50 |
|
51 | This function will receive resolved values from `input` and is expected to return a `Promise<boolean>` or `boolean`.
|
52 |
|
53 | #### options
|
54 |
|
55 | Type: `object`
|
56 |
|
57 | ##### concurrency
|
58 |
|
59 | Type: `number`\
|
60 | Default: `Infinity`\
|
61 | Minimum: `1`
|
62 |
|
63 | The number of concurrently pending promises returned by `tester`.
|
64 |
|
65 | ##### preserveOrder
|
66 |
|
67 | Type: `boolean`\
|
68 | Default: `true`
|
69 |
|
70 | Preserve `input` order when searching.
|
71 |
|
72 | Disable 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>
|