Pass a promise and an abort signal and await the result.
import { raceSignal } from 'race-signal'const controller = new AbortController()const promise = new Promise((resolve, reject) => { setTimeout(() => { resolve('a value') }, 1000)})setTimeout(() => { controller.abort()}, 500)// throws an AbortErrorconst resolve = await raceSignal(promise, controller.signal) Copy
import { raceSignal } from 'race-signal'const controller = new AbortController()const promise = new Promise((resolve, reject) => { setTimeout(() => { resolve('a value') }, 1000)})setTimeout(() => { controller.abort()}, 500)// throws an AbortErrorconst resolve = await raceSignal(promise, controller.signal)
By default the thrown error is the .reason property of the signal but it's possible to override this behaviour with the translateError option:
.reason
translateError
import { raceSignal } from 'race-signal'const controller = new AbortController()const promise = new Promise((resolve, reject) => { setTimeout(() => { resolve('a value') }, 1000)})setTimeout(() => { controller.abort()}, 500)// throws `Error('Oh no!')`const resolve = await raceSignal(promise, controller.signal, { translateError: (signal) => { // use `signal`, or don't return new Error('Oh no!') }}) Copy
import { raceSignal } from 'race-signal'const controller = new AbortController()const promise = new Promise((resolve, reject) => { setTimeout(() => { resolve('a value') }, 1000)})setTimeout(() => { controller.abort()}, 500)// throws `Error('Oh no!')`const resolve = await raceSignal(promise, controller.signal, { translateError: (signal) => { // use `signal`, or don't return new Error('Oh no!') }})
Pass a promise and an abort signal and await the result.
Example: Basic usage
Example: Overriding errors
By default the thrown error is the
.reason
property of the signal but it's possible to override this behaviour with thetranslateError
option: