Home

Awesome

p-race

A better Promise.race()

Improvements:

Install

npm install p-race

Usage

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<Promise | unknown>

executor

Type: signal => Iterable<Promise | unknown>

signal

Type: 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.

import pRace from 'p-race';

pRace(signal => [
	fetch('/api', {signal}),
	setTimeout(10, {signal}),
]);
// Remaining promises other than first one will be aborted.

Related