Projekt

Obecné

Profil

Stáhnout (2.03 KB) Statistiky
| Větev: | Revize:
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

    
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

    
8
## Install
9

    
10
```
11
$ npm install p-locate
12
```
13

    
14

    
15
## Usage
16

    
17
Here we find the first file that exists on disk, in array order.
18

    
19
```js
20
const pathExists = require('path-exists');
21
const pLocate = require('p-locate');
22

    
23
const 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

    
44
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`.
45

    
46
#### input
47

    
48
Type: `Iterable<Promise|any>`
49

    
50
#### tester(element)
51

    
52
Type: `Function`
53

    
54
Expected to return a `Promise<boolean>` or boolean.
55

    
56
#### options
57

    
58
Type: `Object`
59

    
60
##### concurrency
61

    
62
Type: `number`<br>
63
Default: `Infinity`<br>
64
Minimum: `1`
65

    
66
Number of concurrently pending promises returned by `tester`.
67

    
68
##### preserveOrder
69

    
70
Type: `boolean`<br>
71
Default: `true`
72

    
73
Preserve `input` order when searching.
74

    
75
Disable this to improve performance if you don't care about the order.
76

    
77

    
78
## Related
79

    
80
- [p-map](https://github.com/sindresorhus/p-map) - Map over promises concurrently
81
- [p-filter](https://github.com/sindresorhus/p-filter) - Filter promises concurrently
82
- [p-any](https://github.com/sindresorhus/p-any) - Wait for any promise to be fulfilled
83
- [More…](https://github.com/sindresorhus/promise-fun)
84

    
85

    
86
## License
87

    
88
MIT © [Sindre Sorhus](https://sindresorhus.com)
(4-4/4)