Convert a Promise to a AbortSignal.
import { promiseToSignal } from '@byungi/promise-to-signal'
const delayPromise = ms => new Promise(resolve => setTimeout(resolve, ms))
fetch({
/* ... */
signal: promiseToSignal(delayPromise(3000)), // 👈 Add timeout.
})
settle
(Default) - Wait for Promise to beresolved
orrejected
.resolve
- Wait for Promise to beresolved
.reject
- Wait for Promise to berejected
.
import { signalToPromise } from '@byungi/promise-to-signal'
const controller = new AbortController()
const cancel = () => controller.abort()
/* ... */
await Promise.race([
asyncTask(),
signalToPromise(controller.signal), // 👈 Add cancellation.
])
Instead of resolved, it is rejected with abort's reason.
try {
await Promise.race([
asyncTask(),
signalToPromise(signal, {
rejection: true,
}),
])
} catch (err) {
if (err instanceof DOMException) {
/* ... */
}
}
This option does not support custom errors. Instead, do it like below.
signalToPromise(signal).then(() => {
throw new CustomError()
})
MIT