Merge multiple AbortSignals into a single signal
Table of Contents
Features
- Merges multiple AbortSignals into a single signal.
- Returned signal will be aborted if any of the input signals are aborted.
- Can be used in place of
AbortSignal()
in any function/utility. - Works with both
AbortController().signal
andAbortSignal.timeout()
Browser Support
Latest |
Latest |
Latest |
Latest |
Latest |
Installation
Using npm:
$ npm install multi-signal
Using yarn:
$ yarn add multi-signal
Once the package is installed, you can import
the function:
import multiSignal from 'multi-signal';
You can also use require
:
const multiSignal = require('multi-signal');
Usage
General Use
import multiSignal from 'multi-signal';
// signals
const controller1 = new AbortController();
const controller2 = new AbortController();
const signal1 = controller1.signal;
const signal2 = controller2.signal;
const timeoutSignal = AbortSignal.timeout(2000);
// signals as separate arguments
const signal = multiSignal(signal1, signal2);
// signals as array
const signal = multiSignal([signal1, signal2]);
// different signal types
const signal = multiSignal(signal1, signal2, timeoutSignal);
Using with Fetch
import multiSignal from 'multi-signal';
const controller1 = new AbortController();
const signal = controller1.signal;
const timeoutSignal = AbortSignal.timeout(2000); // 2 sec
fetch('url', { signal: multiSignal(signal, timeoutSignal) })
Using with Axios
import multiSignal from 'multi-signal';
const controller1 = new AbortController();
const controller2 = new AbortController();
const signal1 = controller1.signal;
const signal2 = controller1.signal;
axios.get('url', {
timeout: 2000, // 2 sec
signal: multiSignal(signal1, signal2)
})
Using with addEventListener
import multiSignal from 'multi-signal';
const controller = new AbortController();
const signal = controller.signal;
const timeoutSignal = AbortSignal.timeout(2000); // 2 sec
X.addEventListener('event', (e) => { ... }, {
signal: multiSignal(signal, timeoutSignal)
})
Note: You can use as many AbortSignals as you want in any order.
Troubleshooting
MaxListenersExceededWarning: Possible EventTarget memory leak detected. 11 abort listeners added to [AbortSignal].
1. By default, Node.js has maximum listener limit of 10
. you can increase the limit depending on your use case:
import events from 'events';
events.setMaxListeners(100);
Credits
Inspired by: Proposal: fetch with multiple AbortSignals