UNPKG

2.19 kBMarkdownView Raw
1# p-locate [![Build Status](https://travis-ci.org/sindresorhus/p-locate.svg?branch=master)](https://travis-ci.org/sindresorhus/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
8## Install
9
10```
11$ npm install p-locate
12```
13
14
15## Usage
16
17Here we find the first file that exists on disk, in array order.
18
19```js
20const pathExists = require('path-exists');
21const pLocate = require('p-locate');
22
23const files = [
24 'unicorn.png',
25 'rainbow.png', // Only this one actually exists on disk
26 'pony.png'
27];
28
29(async () => {
30 const foundPath = await pLocate(files, file => pathExists(file));
31
32 console.log(foundPath);
33 //=> 'rainbow'
34})();
35```
36
37*The above is just an example. Use [`locate-path`](https://github.com/sindresorhus/locate-path) if you need this.*
38
39
40## API
41
42### pLocate(input, tester, [options])
43
44Returns 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`.
45
46#### input
47
48Type: `Iterable<Promise | unknown>`
49
50An iterable of promises/values to test.
51
52#### tester(element)
53
54Type: `Function`
55
56This function will receive resolved values from `input` and is expected to return a `Promise<boolean>` or `boolean`.
57
58#### options
59
60Type: `Object`
61
62##### concurrency
63
64Type: `number`<br>
65Default: `Infinity`<br>
66Minimum: `1`
67
68Number of concurrently pending promises returned by `tester`.
69
70##### preserveOrder
71
72Type: `boolean`<br>
73Default: `true`
74
75Preserve `input` order when searching.
76
77Disable this to improve performance if you don't care about the order.
78
79
80## Related
81
82- [p-map](https://github.com/sindresorhus/p-map) - Map over promises concurrently
83- [p-filter](https://github.com/sindresorhus/p-filter) - Filter promises concurrently
84- [p-any](https://github.com/sindresorhus/p-any) - Wait for any promise to be fulfilled
85- [More…](https://github.com/sindresorhus/promise-fun)
86
87
88## License
89
90MIT © [Sindre Sorhus](https://sindresorhus.com)