You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
2.0 KiB

4 years ago
  1. # p-locate [![Build Status](https://travis-ci.org/sindresorhus/p-locate.svg?branch=master)](https://travis-ci.org/sindresorhus/p-locate)
  2. > Get the first fulfilled promise that satisfies the provided testing function
  3. Think of it like an async version of [`Array#find`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find).
  4. ## Install
  5. ```
  6. $ npm install p-locate
  7. ```
  8. ## Usage
  9. Here we find the first file that exists on disk, in array order.
  10. ```js
  11. const pathExists = require('path-exists');
  12. const pLocate = require('p-locate');
  13. const files = [
  14. 'unicorn.png',
  15. 'rainbow.png', // Only this one actually exists on disk
  16. 'pony.png'
  17. ];
  18. (async () => {
  19. const foundPath = await pLocate(files, file => pathExists(file));
  20. console.log(foundPath);
  21. //=> 'rainbow'
  22. })();
  23. ```
  24. *The above is just an example. Use [`locate-path`](https://github.com/sindresorhus/locate-path) if you need this.*
  25. ## API
  26. ### pLocate(input, tester, [options])
  27. 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`.
  28. #### input
  29. Type: `Iterable<Promise|any>`
  30. #### tester(element)
  31. Type: `Function`
  32. Expected to return a `Promise<boolean>` or boolean.
  33. #### options
  34. Type: `Object`
  35. ##### concurrency
  36. Type: `number`<br>
  37. Default: `Infinity`<br>
  38. Minimum: `1`
  39. Number of concurrently pending promises returned by `tester`.
  40. ##### preserveOrder
  41. Type: `boolean`<br>
  42. Default: `true`
  43. Preserve `input` order when searching.
  44. Disable this to improve performance if you don't care about the order.
  45. ## Related
  46. - [p-map](https://github.com/sindresorhus/p-map) - Map over promises concurrently
  47. - [p-filter](https://github.com/sindresorhus/p-filter) - Filter promises concurrently
  48. - [p-any](https://github.com/sindresorhus/p-any) - Wait for any promise to be fulfilled
  49. - [More…](https://github.com/sindresorhus/promise-fun)
  50. ## License
  51. MIT © [Sindre Sorhus](https://sindresorhus.com)