Welcome to the Linux Foundation Forum!

Error in code example, Chapter 9, "Promise-Based Single Use Listener and AbortController"

This code snippet throws an error when run:

import { once, EventEmitter } from 'events'
import { setTimeout } from 'timers/promises'

const sometimesLaggy = new EventEmitter()

const ac = new AbortController()
const { signal } = ac

setTimeout(2000 * Math.random(), null, { signal }).then(() => {
  sometimesLaggy.emit('ping')
})

setTimeout(500).then(() => ac.abort())

try {
  await once(sometimesLaggy, 'ping', { signal })
  console.log('pinged!')
} catch (err) {
  // ignore abort errors:
  if (err.code !== 'ABORT_ERR') throw err
  console.log('canceled')
} 

Error:

node:timers/promises:47
    reject(new AbortError(undefined, { cause: signal?.reason }));
           ^
AbortError: The operation was aborted
code: 'ABORT_ERR',
  [cause]: DOMException [AbortError]: This operation was aborted

If I don't pass the AbortSignal instance to setTimeout() it works as expected.
I guess what we really should do is to add an error handler like so:

setTimeout(2000 * Math.random(), null, { signal }).then(() => {
  sometimesLaggy.emit('ping')
}).catch(() => console.log("Don't throw error on reject!");

Categories

Upcoming Training