├── .editorconfig ├── .gitattributes ├── .github ├── security.md └── workflows │ └── main.yml ├── .gitignore ├── .npmrc ├── index.d.ts ├── index.js ├── index.test-d.ts ├── license ├── package.json ├── readme.md └── test.js /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = tab 5 | end_of_line = lf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | 10 | [*.yml] 11 | indent_style = space 12 | indent_size = 2 13 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf 2 | -------------------------------------------------------------------------------- /.github/security.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. 4 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | - push 4 | - pull_request 5 | jobs: 6 | test: 7 | name: Node.js ${{ matrix.node-version }} 8 | runs-on: ubuntu-latest 9 | strategy: 10 | fail-fast: false 11 | matrix: 12 | node-version: 13 | - 20 14 | - 18 15 | steps: 16 | - uses: actions/checkout@v4 17 | - uses: actions/setup-node@v4 18 | with: 19 | node-version: ${{ matrix.node-version }} 20 | - run: npm install 21 | - run: npm test 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | yarn.lock 3 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false 2 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | import type {Options} from 'p-map'; 2 | 3 | /** 4 | Filter promises concurrently. 5 | 6 | @param input - Iterated over concurrently in the `filterer` function. 7 | @param filterer - The filterer function that decides whether an element should be included into result. 8 | 9 | @example 10 | ``` 11 | import pFilter from 'p-filter'; 12 | import getWeather from 'get-weather'; // Not a real module 13 | 14 | const places = [ 15 | getCapital('Norway').then(info => info.name), 16 | 'Bangkok, Thailand', 17 | 'Berlin, Germany', 18 | 'Tokyo, Japan', 19 | ]; 20 | 21 | const filterer = async place => { 22 | const weather = await getWeather(place); 23 | return weather.temperature > 30; 24 | }; 25 | 26 | const result = await pFilter(places, filterer); 27 | 28 | console.log(result); 29 | //=> ['Bangkok, Thailand'] 30 | ``` 31 | */ 32 | export default function pFilter( 33 | input: Iterable>, 34 | filterer: ( 35 | element: ValueType, 36 | index: number 37 | ) => boolean | PromiseLike, 38 | options?: Options 39 | ): Promise; 40 | 41 | /** 42 | Filter promises concurrently. 43 | 44 | @param input - Iterated over concurrently in the `filterer` function. 45 | @param filterer - The filterer function that decides whether an element should be included into result. 46 | @param options - See the [`p-map` options](https://github.com/sindresorhus/p-map#options). 47 | @returns An async iterable that iterates over the promises in `iterable` and ones returned from `filterer` concurrently, calling `filterer` for each element. 48 | 49 | @example 50 | ``` 51 | import {pFilterIterable} from 'p-filter'; 52 | import getWeather from 'get-weather'; // Not a real module 53 | 54 | async function * getPlaces() { 55 | const name = await getCapital('Norway'); 56 | 57 | yield name; 58 | yield 'Bangkok, Thailand'; 59 | yield 'Berlin, Germany'; 60 | yield 'Tokyo, Japan'; 61 | } 62 | 63 | const places = getPlaces(); 64 | 65 | const filterer = async place => { 66 | const weather = await getWeather(place); 67 | return weather.temperature > 30; 68 | }; 69 | 70 | for await (const element of pFilterIterable(places, filterer)) { 71 | console.log(element); 72 | } 73 | //=> ['Bangkok, Thailand'] 74 | ``` 75 | */ 76 | export function pFilterIterable( 77 | input: 78 | | AsyncIterable> 79 | | Iterable>, 80 | filterer: ( 81 | element: ValueType, 82 | index: number 83 | ) => boolean | PromiseLike, 84 | options?: Options 85 | ): AsyncIterable; 86 | 87 | export {Options} from 'p-map'; 88 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | import pMap, {pMapIterable} from 'p-map'; 2 | 3 | export default async function pFilter(iterable, filterer, options) { 4 | const values = await pMap( 5 | iterable, 6 | (element, index) => Promise.all([filterer(element, index), element]), 7 | options, 8 | ); 9 | 10 | return values.filter(value => Boolean(value[0])).map(value => value[1]); 11 | } 12 | 13 | export function pFilterIterable(iterable, filterer, options) { 14 | const values = pMapIterable( 15 | iterable, 16 | (element, index) => Promise.all([filterer(element, index), element]), 17 | options, 18 | ); 19 | 20 | return { 21 | async * [Symbol.asyncIterator]() { 22 | for await (const [value, element] of values) { 23 | if (value) { 24 | yield element; 25 | } 26 | } 27 | }, 28 | }; 29 | } 30 | -------------------------------------------------------------------------------- /index.test-d.ts: -------------------------------------------------------------------------------- 1 | import {expectType} from 'tsd'; 2 | import pFilter, {pFilterIterable} from './index.js'; 3 | 4 | const places = [ 5 | 'Bangkok, Thailand', 6 | 'Berlin, Germany', 7 | Promise.resolve('Tokyo, Japan'), 8 | ]; 9 | 10 | expectType>( 11 | pFilter(places, async place => 12 | place === 'Bangkok, Thailand' ? true : Promise.resolve(false), 13 | ), 14 | ); 15 | expectType>( 16 | pFilter(new Set([1, 2]), number => number > 1, {concurrency: 1}), 17 | ); 18 | 19 | expectType>( 20 | pFilterIterable(places, async place => 21 | place === 'Bangkok, Thailand' ? true : Promise.resolve(false), 22 | ), 23 | ); 24 | 25 | async function * getPlaces(): AsyncIterable { 26 | yield 'Bangkok, Thailand'; 27 | yield 'Berlin, Germany'; 28 | yield 'Tokyo, Japan'; 29 | } 30 | 31 | expectType>( 32 | pFilterIterable(getPlaces(), async place => 33 | place === 'Bangkok, Thailand' ? true : Promise.resolve(false), 34 | ), 35 | ); 36 | 37 | expectType>( 38 | pFilterIterable(new Set([1, 2]), number => number > 1, {concurrency: 1}), 39 | ); 40 | -------------------------------------------------------------------------------- /license: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Sindre Sorhus (https://sindresorhus.com) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "p-filter", 3 | "version": "4.1.0", 4 | "description": "Filter promises concurrently", 5 | "license": "MIT", 6 | "repository": "sindresorhus/p-filter", 7 | "funding": "https://github.com/sponsors/sindresorhus", 8 | "author": { 9 | "name": "Sindre Sorhus", 10 | "email": "sindresorhus@gmail.com", 11 | "url": "https://sindresorhus.com" 12 | }, 13 | "type": "module", 14 | "exports": { 15 | "types": "./index.d.ts", 16 | "default": "./index.js" 17 | }, 18 | "sideEffects": false, 19 | "engines": { 20 | "node": ">=18" 21 | }, 22 | "scripts": { 23 | "test": "xo && ava && tsd" 24 | }, 25 | "files": [ 26 | "index.js", 27 | "index.d.ts" 28 | ], 29 | "keywords": [ 30 | "promise", 31 | "filter", 32 | "collection", 33 | "iterable", 34 | "iterator", 35 | "fulfilled", 36 | "async", 37 | "await", 38 | "promises", 39 | "concurrently", 40 | "concurrency", 41 | "parallel" 42 | ], 43 | "dependencies": { 44 | "p-map": "^7.0.1" 45 | }, 46 | "devDependencies": { 47 | "ava": "^6.0.1", 48 | "tsd": "^0.30.1", 49 | "xo": "^0.56.0" 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # p-filter 2 | 3 | > Filter promises concurrently 4 | 5 | Useful when you need to run promise-returning & async functions multiple times with different inputs concurrently and get a filtered down result. 6 | 7 | ## Install 8 | 9 | ```sh 10 | npm install p-filter 11 | ``` 12 | 13 | ## Usage 14 | 15 | ```js 16 | import pFilter from 'p-filter'; 17 | import getWeather from 'get-weather'; // Not a real module 18 | 19 | const places = [ 20 | getCapital('Norway').then(info => info.name), 21 | 'Bangkok, Thailand', 22 | 'Berlin, Germany', 23 | 'Tokyo, Japan', 24 | ]; 25 | 26 | const filterer = async place => { 27 | const weather = await getWeather(place); 28 | return weather.temperature > 30; 29 | }; 30 | 31 | const result = await pFilter(places, filterer); 32 | 33 | console.log(result); 34 | //=> ['Bangkok, Thailand'] 35 | ``` 36 | 37 | ## API 38 | 39 | ### pFilter(input, filterer, options?) 40 | 41 | Returns a `Promise` that is fulfilled when all promises in `input` and ones returned from `filterer` are fulfilled, or rejects if any of the promises reject. The fulfilled value is an `Array` of the fulfilled values returned from `filterer` in `input` order. 42 | 43 | #### input 44 | 45 | Type: `Iterable | unknown>` 46 | 47 | Iterated over concurrently in the `filterer` function. 48 | 49 | #### filterer(element, index) 50 | 51 | Type: `Function` 52 | 53 | The filterer function that decides whether an element should be included into result. Expected to return `boolean | Promise`. 54 | 55 | #### options 56 | 57 | Type: `object` 58 | 59 | See the [`p-map` options](https://github.com/sindresorhus/p-map#options). 60 | 61 | ##### concurrency 62 | 63 | Type: `number`\ 64 | Default: `Infinity`\ 65 | Minimum: `1` 66 | 67 | The number of concurrently pending promises returned by `filterer`. 68 | 69 | ### pFilterIterable(iterable, filterer, options?) 70 | 71 | Returns an async iterable that iterates over the promises in `iterable` and ones returned from `filterer` concurrently, calling `filterer` for each element. 72 | 73 | ```js 74 | import {pFilterIterable} from 'p-filter'; 75 | import getWeather from 'get-weather'; // Not a real module 76 | 77 | async function * getPlaces() { 78 | const name = await getCapital('Norway'); 79 | 80 | yield name; 81 | yield 'Bangkok, Thailand'; 82 | yield 'Berlin, Germany'; 83 | yield 'Tokyo, Japan'; 84 | } 85 | 86 | const places = getPlaces(); 87 | 88 | const filterer = async place => { 89 | const weather = await getWeather(place); 90 | return weather.temperature > 30; 91 | }; 92 | 93 | for await (const element of pFilterIterable(places, filterer)) { 94 | console.log(element); 95 | } 96 | //=> ['Bangkok, Thailand'] 97 | ``` 98 | 99 | #### iterable 100 | 101 | Type: `Iterable | unknown>` 102 | 103 | Iterated over concurrently in the `filterer` function. 104 | 105 | #### filterer(element, index) 106 | 107 | Type: `Function` 108 | 109 | The filterer function that decides whether an element should be included into result. Expected to return `boolean | Promise`. 110 | 111 | #### options 112 | 113 | Type: `object` 114 | 115 | See the [`p-map` options](https://github.com/sindresorhus/p-map#options). 116 | 117 | ##### concurrency 118 | 119 | Type: `number`\ 120 | Default: `Infinity`\ 121 | Minimum: `1` 122 | 123 | The number of concurrently pending promises returned by `filterer`. 124 | 125 | ## Related 126 | 127 | - [p-locate](https://github.com/sindresorhus/p-locate) - Get the first fulfilled promise that satisfies the provided testing function 128 | - [p-map](https://github.com/sindresorhus/p-map) - Map over promises concurrently 129 | - [p-times](https://github.com/sindresorhus/p-times) - Run promise-returning & async functions a specific number of times concurrently 130 | - [More…](https://github.com/sindresorhus/promise-fun) 131 | -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | import test from 'ava'; 2 | import pFilter, {pFilterIterable} from './index.js'; 3 | 4 | // See `p-map` for more comprehensive tests 5 | test('main', async t => { 6 | t.deepEqual( 7 | await pFilter([Promise.resolve(1), 2, 3, 4], x => x % 2), 8 | [1, 3], 9 | ); 10 | t.deepEqual( 11 | await pFilter([1, 2, 3, 4], x => Promise.resolve(x % 2)), 12 | [1, 3], 13 | ); 14 | }); 15 | 16 | test('handles empty iterable', async t => { 17 | t.deepEqual(await pFilter([]), []); 18 | }); 19 | 20 | test('pFilterIterable', async t => { 21 | const iterableToArray = async iterable => { 22 | const array = []; 23 | for await (const item of iterable) { 24 | array.push(item); 25 | } 26 | 27 | return array; 28 | }; 29 | 30 | const rangeIterable = { 31 | async * [Symbol.asyncIterator]() { 32 | yield 1; 33 | yield 2; 34 | yield 3; 35 | yield 4; 36 | }, 37 | }; 38 | t.deepEqual( 39 | await iterableToArray(pFilterIterable(rangeIterable, x => x % 2)), 40 | [1, 3], 41 | ); 42 | 43 | t.deepEqual( 44 | await iterableToArray( 45 | pFilterIterable(rangeIterable, x => Promise.resolve(x % 2)), 46 | ), 47 | [1, 3], 48 | ); 49 | 50 | t.deepEqual( 51 | await iterableToArray( 52 | pFilterIterable([Promise.resolve(1), 2, 3, 4], x => x % 2), 53 | ), 54 | [1, 3], 55 | ); 56 | t.deepEqual( 57 | await iterableToArray( 58 | pFilterIterable([1, 2, 3, 4], x => Promise.resolve(x % 2)), 59 | ), 60 | [1, 3], 61 | ); 62 | t.deepEqual(await iterableToArray(pFilterIterable([])), []); 63 | }); 64 | --------------------------------------------------------------------------------