multi-signal
TypeScript icon, indicating that this package has built-in type declarations

1.0.3 • Public • Published

Multi Signal

Merge multiple AbortSignals into a single signal

Blog PostGitHub Repository

npm version install size npm bundle size npm downloads Known Vulnerabilities

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 and AbortSignal.timeout()

Browser Support

Edge Chrome Safari Firefox Opera
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

1. MaxListenersExceededWarning: Possible EventTarget memory leak detected. 11 abort listeners added to [AbortSignal].

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

License

MIT

Readme

Keywords

Package Sidebar

Install

npm i multi-signal

Weekly Downloads

4

Version

1.0.3

License

MIT

Unpacked Size

8.61 kB

Total Files

5

Last publish

Collaborators

  • rashidshamloo