Skip to content

mstuart/abort-race

Repository files navigation

abort-race

Race multiple async operations with automatic AbortSignal cleanup for losers

Install

npm install abort-race

Usage

import abortRace from 'abort-race';

const result = await abortRace([
	async signal => {
		const response = await fetch('https://api1.example.com', {signal});
		return response.json();
	},
	async signal => {
		const response = await fetch('https://api2.example.com', {signal});
		return response.json();
	},
]);

console.log(result);
// The response from whichever API responded first.
// The other request was automatically aborted.

API

abortRace(tasks, options?)

Race multiple async operations. The first task to resolve wins, and all other tasks are automatically aborted via their AbortSignal. If a task throws, all others are aborted and the error is re-thrown.

Returns a Promise that resolves with the winning task's result.

tasks

Type: Array<(signal: AbortSignal) => Promise<T>>

An array of functions that each receive an AbortSignal and return a Promise.

options

Type: object

signal

Type: AbortSignal

An external AbortSignal for cancelling all tasks. When this signal aborts, all tasks are aborted.

Related

License

MIT

About

Race multiple async operations with automatic AbortSignal cleanup for losers

Resources

License

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors