├── .npmrc ├── .gitattributes ├── .gitignore ├── .editorconfig ├── index.test-d.ts ├── .github └── workflows │ └── main.yml ├── index.js ├── package.json ├── index.d.ts ├── license ├── test.js └── readme.md /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false 2 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | yarn.lock 3 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /index.test-d.ts: -------------------------------------------------------------------------------- 1 | import {expectType} from 'tsd'; 2 | import pRace from './index.js'; 3 | 4 | expectType>(pRace(['foo', Promise.resolve('bar')])); 5 | expectType>(pRace(new Set([1, Promise.resolve(2)]))); 6 | expectType>(pRace(() => ['foo', Promise.resolve('bar')])); 7 | expectType>(pRace(() => new Set([1, Promise.resolve(2)]))); 8 | -------------------------------------------------------------------------------- /.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 | - 14 14 | - 12 15 | steps: 16 | - uses: actions/checkout@v2 17 | - uses: actions/setup-node@v2 18 | with: 19 | node-version: ${{ matrix.node-version }} 20 | - run: npm install 21 | - run: npm test 22 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | import isEmptyIterable from 'is-empty-iterable'; 2 | 3 | const toIterable = (executorOrIterable, signal) => { 4 | return typeof executorOrIterable === 'function' ? executorOrIterable(signal) : executorOrIterable; 5 | }; 6 | 7 | export default async function pRace(executorOrIterable) { 8 | const abortController = globalThis.AbortController ? new AbortController() : undefined; 9 | 10 | const iterable = toIterable(executorOrIterable, abortController ? abortController.signal : undefined); 11 | 12 | if (isEmptyIterable(iterable)) { 13 | throw new RangeError('Expected the iterable to contain at least one item'); 14 | } 15 | 16 | const result = await Promise.race(iterable); 17 | 18 | if (abortController) { 19 | abortController.abort(); 20 | } 21 | 22 | return result; 23 | } 24 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "p-race", 3 | "version": "3.1.0", 4 | "description": "A better `Promise.race()`", 5 | "license": "MIT", 6 | "repository": "sindresorhus/p-race", 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": "./index.js", 15 | "engines": { 16 | "node": ">=12" 17 | }, 18 | "scripts": { 19 | "test": "xo && ava && tsd" 20 | }, 21 | "files": [ 22 | "index.js", 23 | "index.d.ts" 24 | ], 25 | "keywords": [ 26 | "promise", 27 | "race", 28 | "better", 29 | "async", 30 | "await", 31 | "promises", 32 | "bluebird" 33 | ], 34 | "dependencies": { 35 | "is-empty-iterable": "^3.0.0" 36 | }, 37 | "devDependencies": { 38 | "ava": "^3.15.0", 39 | "delay": "^5.0.0", 40 | "tsd": "^0.14.0", 41 | "xo": "^0.38.2" 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | type IterableOfPromiseLike = Iterable>; 2 | 3 | /** 4 | A better [`Promise.race()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/race). 5 | 6 | This fixes the [silly behavior](https://github.com/domenic/promises-unwrapping/issues/75) of `Promise.race()` returning a forever pending promise when supplied an empty iterable, which could create some really hard to debug problems. 7 | 8 | @example 9 | ``` 10 | import pRace from 'p-race'; 11 | 12 | Promise.race([]); 13 | // Returns a forever pending promise… 14 | 15 | pRace([]); 16 | //=> [RangeError: Expected the input to contain at least one item] 17 | 18 | pRace(signal => [ 19 | fetch('/api', {signal}), 20 | setTimeout(10, {signal}), 21 | ]); 22 | //=> Remaining promises other than first one will be aborted. 23 | ``` 24 | */ 25 | export default function pRace(iterableOrExecutor: (IterableOfPromiseLike) | ((signal: AbortSignal) => IterableOfPromiseLike)): Promise; 26 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | import test from 'ava'; 2 | import delay from 'delay'; 3 | import pRace from './index.js'; 4 | 5 | test('works like Promise.race()', async t => { 6 | t.is(await pRace([delay(50, {value: 1}), delay(100, {value: 2})]), 1); 7 | }); 8 | 9 | test('handles empty Iterable', async t => { 10 | await t.throwsAsync(pRace([]), {instanceOf: RangeError}); 11 | }); 12 | 13 | if (globalThis.AbortController !== undefined) { 14 | test('abortsignal', async t => { 15 | let signalReference; 16 | 17 | t.is(await pRace(signal => { 18 | signalReference = signal; 19 | 20 | return [ 21 | delay(50, {value: 1, signal}), 22 | delay(100, {value: 2, signal}) 23 | ]; 24 | }), 1); 25 | 26 | t.true(signalReference.aborted); 27 | }); 28 | 29 | test('abortsignal - should throw error', async t => { 30 | let signalReference; 31 | 32 | await t.throwsAsync( 33 | pRace(signal => { 34 | signalReference = signal; 35 | 36 | return [ 37 | delay(50, {value: Promise.reject(new Error('some error')), signal}), 38 | delay(100, {value: 1, signal}) 39 | ]; 40 | }), { 41 | message: 'some error' 42 | } 43 | ); 44 | 45 | t.false(signalReference.aborted); 46 | }); 47 | } 48 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # p-race 2 | 3 | > A better [`Promise.race()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/race) 4 | 5 | Improvements: 6 | - Fixes the [silly behavior](https://github.com/domenic/promises-unwrapping/issues/75) of `Promise.race()` returning a forever pending promise when supplied an empty iterable, which could create some really hard to debug problems. `Promise.race()` returns the first promise to fulfill or reject. Check out [`p-any`](https://github.com/sindresorhus/p-any) if you like to get the first promise to fulfill. 7 | - Supports aborting promises using [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal). 8 | 9 | ## Install 10 | 11 | ```sh 12 | npm install p-race 13 | ``` 14 | 15 | ## Usage 16 | 17 | ```js 18 | import pRace from 'p-race'; 19 | 20 | Promise.race([]); 21 | // Returns a forever pending promise… 22 | 23 | pRace([]); 24 | //=> [RangeError: Expected the input to contain at least one item] 25 | ``` 26 | 27 | ## API 28 | 29 | ### pRace(iterable | executor) 30 | 31 | #### iterable 32 | 33 | Type: `Iterable` 34 | 35 | #### executor 36 | 37 | Type: `signal => Iterable` 38 | 39 | ##### signal 40 | 41 | Type: [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) 42 | 43 | You can pass the `signal` to each iterable's element to abort remaining promises when resolve the first promise. 44 | 45 | *Requires Node.js 16 or later.* 46 | 47 | ```js 48 | import pRace from 'p-race'; 49 | 50 | pRace(signal => [ 51 | fetch('/api', {signal}), 52 | setTimeout(10, {signal}), 53 | ]); 54 | // Remaining promises other than first one will be aborted. 55 | ``` 56 | 57 | ## Related 58 | 59 | - [p-any](https://github.com/sindresorhus/p-any) - Wait for any promise to be fulfilled 60 | - [More…](https://github.com/sindresorhus/promise-fun) 61 | --------------------------------------------------------------------------------