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:

  1. import { once, EventEmitter } from 'events'
  2. import { setTimeout } from 'timers/promises'
  3.  
  4. const sometimesLaggy = new EventEmitter()
  5.  
  6. const ac = new AbortController()
  7. const { signal } = ac
  8.  
  9. setTimeout(2000 * Math.random(), null, { signal }).then(() => {
  10. sometimesLaggy.emit('ping')
  11. })
  12.  
  13. setTimeout(500).then(() => ac.abort())
  14.  
  15. try {
  16. await once(sometimesLaggy, 'ping', { signal })
  17. console.log('pinged!')
  18. } catch (err) {
  19. // ignore abort errors:
  20. if (err.code !== 'ABORT_ERR') throw err
  21. console.log('canceled')
  22. }

Error:

  1. node:timers/promises:47
  2. reject(new AbortError(undefined, { cause: signal?.reason }));
  3. ^
  4. AbortError: The operation was aborted
  5. code: 'ABORT_ERR',
  6. [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:

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

Welcome!

It looks like you're new here. Sign in or register to get started.
Sign In

Welcome!

It looks like you're new here. Sign in or register to get started.
Sign In

Categories

Upcoming Training