https://github.com/sindresorhus/p-race
A better `Promise.race()`
https://github.com/sindresorhus/p-race
Last synced: 3 months ago
JSON representation
A better `Promise.race()`
- Host: GitHub
- URL: https://github.com/sindresorhus/p-race
- Owner: sindresorhus
- License: mit
- Created: 2016-10-21T06:33:32.000Z (about 9 years ago)
- Default Branch: main
- Last Pushed: 2022-12-13T15:14:20.000Z (almost 3 years ago)
- Last Synced: 2025-08-08T23:29:15.741Z (4 months ago)
- Language: JavaScript
- Size: 13.7 KB
- Stars: 46
- Watchers: 5
- Forks: 5
- Open Issues: 0
-
Metadata Files:
- Readme: readme.md
- License: license
Awesome Lists containing this project
- promise-fun - p-race
- awesome-promises - p-race - A better `Promise.race()` (Convenience Utilities / sindresorhus's many Promise utilities ([see notes](https://github.com/sindresorhus/promise-fun)))
- fucking-awesome-promises - p-race - A better `Promise.race()` (Convenience Utilities / sindresorhus's many Promise utilities (<b><code> 5075⭐</code></b> <b><code> 136🍴</code></b> [see notes](https://github.com/sindresorhus/promise-fun))))
README
# p-race
> A better [`Promise.race()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/race)
Improvements:
- 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.
- Supports aborting promises using [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal).
## Install
```sh
npm install p-race
```
## Usage
```js
import pRace from 'p-race';
Promise.race([]);
// Returns a forever pending promise…
pRace([]);
//=> [RangeError: Expected the input to contain at least one item]
```
## API
### pRace(iterable | executor)
#### iterable
Type: `Iterable`
#### executor
Type: `signal => Iterable`
##### signal
Type: [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)
You can pass the `signal` to each iterable's element to abort remaining promises when resolve the first promise.
*Requires Node.js 16 or later.*
```js
import pRace from 'p-race';
pRace(signal => [
fetch('/api', {signal}),
setTimeout(10, {signal}),
]);
// Remaining promises other than first one will be aborted.
```
## Related
- [p-any](https://github.com/sindresorhus/p-any) - Wait for any promise to be fulfilled
- [More…](https://github.com/sindresorhus/promise-fun)