Skip to content

Cannot cleanup exit handler inside the handler itself #85

@ehmicky

Description

@ehmicky

Bug

The following:

import { onExit } from 'signal-exit'

const cleanup = onExit(() => {
  console.log('A')
  cleanup()
})

onExit(() => {
  console.log('B')
})

Prints:

A

But should print:

A
B

Reason

When the exit is happening, signal-exit is iterating over the exit handlers here:

for (const fn of this.listeners[ev]) {

However, cleanup() ends up calling:

list.splice(i, 1)

Which directly mutates this.listeners. This makes the iteration above not work anymore, due to mutating an array while iterating on it. Instead, the following would work:

    for (const fn of [...this.listeners[ev]]) {

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions